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;
}
}