博客 分类专栏 专题 成员
Java Stram应用
2023-05-15 03:48:43
分类专栏: Java

filter 过滤


List resultUserList = list.stream().filter(user -> user.getDepartmentId() == 1).collect(Collectors.toList());


map


List userNameList = list.stream().map(user -> user.getName()).collect(Collectors.toList());


distinct 去重


 List distinctUsers = list.stream().distinct().collect(Collectors.toList());


根据某个属性去重


  List distinctUsers2 = list.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getUserId()))),                ArrayList::new));


排序

升序

List sortUserList = list.stream().sorted(Comparator.comparing(User::getUserId).reversed()).collect(Collectors.toList());

降序


List sortUserList = list.stream().sorted(Comparator.comparing(User::getUserId)).collect(Collectors.toList());

toMap 数组转为Map


Map useMap = list.stream().collect(Collectors.toMap(user -> user.getUserId(), Function.identity()));

重复的key报错,取其中一个key

Map useMap2 = list.stream().collect(Collectors.toMap(user -> user.getUserId(), Function.identity(), (data1, data2) -> data2));

groupingBy 分组

 Map> departmentMap = list.stream().collect(Collectors.groupingBy(User::getDepartmentId));

joining 连接


 String userNames = list.stream().map(user -> user.getName()).collect(Collectors.joining(","));


minBy 取最小值


 User minUserId = list.stream().collect(Collectors.minBy(Comparator.comparingInt(user -> user.getUserId()))).get();


maxBy 取最大值


User maxUserId = list.stream().collect(Collectors.maxBy(Comparator.comparingInt(user -> user.getUserId()))).get();


count 求总数量


   Long count = list.stream().filter(user -> user.getDepartmentId() == 2).count();


sum求和


Integer sum = list.stream().mapToInt(user -> user.getUserId()).sum();


anyMatch 是否匹配


Boolean matchAny = list.stream().anyMatch(user -> "赵六".equals(user.getName()));