Java 高效率 List集合扩展工具类

package utils;

import com.google.common.collect.Lists;
import org.checkerframework.checker.units.qual.K;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 集合工具类
 * @author: admin
 */
public class CollectionUtil extends cn.hutool.core.collection.CollectionUtil {

    /**
     * 返回集合属性List集合
     */
    public static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {
        return from.stream().map(func).collect(Collectors.toList());
    }

    /**
     * 返回集合属性Set集合
     */
    public static <T, U> Set<U> convertSet(List<T> from, Function<T, U> func) {
        return from.stream().map(func).collect(Collectors.toSet());
    }

    /**
     * 返回 同一对象(key->属性 value->属性)map
     */
    public static <T, K, V> Map<K, V> convertMapKeyValue(List<T> from, Function<T, K> keyFunc, Function<T, V> valueFunc) {
        return from.stream().collect(Collectors.toMap(keyFunc, valueFunc,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    }

    /**
     * 返回 同一对象(key->属性 value->对象)map
     */
    public static <T, K> Map<K, T> convertMapKey(List<T> from, Function<T, K> keyFunc) {
        return from.stream().collect(Collectors.toMap(keyFunc, item -> item,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));
    }

    /**
     * 返回 分组 map
     */
    public static <T, K> Map<K, List<T>> groupMapKey(List<T> from, Function<T, K> keyFunc) {
        return from.stream().collect(Collectors.groupingBy(keyFunc));
    }

    /**
     * 返回 排序的list
     */
    public static <T, U extends Comparable<? super U>> List<T> orderBy(List<T> list, Function<? super T, ? extends U> keyExtractor) {
        return list.stream().sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList());
    }

    /**
     * fromList<E>->targetList<T>
     */
    public static <E, T> List<T> toTargetList(Collection<E> fromList, Class<T> t) {
        List<T> list = Lists.newArrayList();
        fromList.forEach(s -> {
            T to = null;
            if (s instanceof Map) {
                try {
                    to = com.baomidou.mybatisplus.core.toolkit.BeanUtils.mapToBean((Map<String, Object>) s, t);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    to = t.getDeclaredConstructor().newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                BeanUtils.copyProperties(s, to);
            }
            list.add(to);
        });
        return list;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值