分组
Map<Integer, List<T>> group = List.stream().collect(Collectors.groupingBy(T::getField));
排序
// 升序
List<T> list = List.stream().sorted(Comparator.comparing(T::getSize)).collect(Collectors.toList());
// 倒序
List<T> list = List.stream().sorted(Comparator.comparing(T::getSize).reversed()).collect(Collectors.toList());
条件查询
// 非boolean ListUtil.where(List, x -> "LL".equals("LL")); // boolean ListUtil.where(List, T::isLL);
封装
import java.util.*; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; public class ListUtil { /** * 判断集合是否有值 * * @param list * @return */ public static <TOrigin> boolean isAny(List<TOrigin> list) { return list != null && list.size() > 0; } /** * 判断map是否有值 * * @param map * @return */ public static <Key, Value> boolean isAny(Map<Key, Value> map) { return map != null && map.size() > 0; } /** * 获取范围集合行 * * @param list 集合 * @param skip 跳过多少行:pagesiz*pageindex * @param take 获取多少行:pagesize */ public static <TOrigin> ArrayList<TOrigin> getRange(List<TOrigin> list, Integer skip, Integer take) { ArrayList<TOrigin> itemList = new ArrayList<>(); if (skip < list.size()) { Integer max = skip + take; if (max > list.size()) { max = list.size(); } for (Integer i = skip; i < max; i++) { itemList.add(list.get(i)); } } return itemList; } /** * 扩展where方法 * * @param source 数据源 * @param predicate 表达式 */ public static <TOrigin> List<TOrigin> where(List<TOrigin> source, Predicate<? super TOrigin> predicate) { // 判断当前关键字缓存是否已存在 Stream<TOrigin> stream = source.stream().filter(predicate); //将Stream转化为List List<TOrigin> list = stream.collect(Collectors.toList()); return list; } /** * 扩展 去重 方法 * * @param source 数据源 */ public static <TOrigin> List<TOrigin> distinct(List<TOrigin> source) { Set set = new HashSet(); List newList = new ArrayList(); set.addAll(source); newList.addAll(set); return newList; } /** * 获取最小值 * @param sourceList 数据源集合 * @param keyExtractor 需要获取最小值的属性 * */ public static <TOrigin, TAttribute extends Comparable<? super TAttribute>> TOrigin min(List<TOrigin> sourceList, Function<? super TOrigin, ? extends TAttribute> keyExtractor) { return sourceList.stream().min(Comparator.comparing(keyExtractor)).get(); } }