Java List collect集合操作集锦


一、根据某个List中的key来过滤出最大(或者最小)的一条数据

 Optional<UserInfo> UserInfoCheckOp= reviewUser
.stream()
.max(Comparator.comparing(UserInfo::getOrgType));


二、将List中的某个key中的数据转换成List数组

List<String> persionList = reviewList
.stream()
.map(UserInfo::getUserName).collect(Collectors.toList());


三、通过某个值过滤List中的数据

List<UserInfo> reviewUserList = reviewUser
.stream()
.filter(u -> "1".equals(u.getOrgType())).collect(Collectors.toList());


三.1 过滤方法二

创建一个方法:

public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
}

去重举例:

List<User> users = new LinkedList<>();
users.add(new User("Jim"));
users.add(new User("Jim"));
users.add(new User("Tom"));
users.add(new User("Leo"));
List<User> distinctUsers = users.stream()
        .filter(distinctByKey(User::getName))
        .collect(Collectors.toList());
System.out.println(distinctUsers);//[Jim, Tom, Leo]

四、List去重

List<UserInfo> reviewUserList = reviewUser.stream().distinct().collect(Collectors.toList());


五、List  Collectors.groupingBy排序

移步→https://www.bemhome.com/post/16.html


qrcode