• 欢迎访问本站,本站记录博主日常编程遇到的问题,知识,惊奇软件等。如有问题还请留言


    Deprecated: strip_tags(): Passing null to parameter #1 ($string) of type string is deprecated in /www/wwwroot/gschaos.club/wp-content/themes/Git-alpha-6h0SRk/header.php on line 294

Java8 Lambda实现条件去重distinct List

java mysticalycc 3年前 (2023-02-27) 599次浏览 已收录 0个评论

java8 lambda实现条件去重distinct List

我们知道, java8 lambda自带的去重为 distinct 方法, 但是只能过滤整体对象, 不能实现对象里的某个值进行判定去重, 比如:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 5, 5, 5, 6, 7);

List<Integer> distinctNumbers = numbers.stream()
.distinct()
.collect(Collectors.toList());
System.out.println(distinctNumbers);//1, 2, 3, 4, 5, 6, 7

但是, 如果我们有一个 List 类似这样的对象, 要对 User 的 name 进行条件去重怎么办?
我们想要的效果是这样的:

List<User> distinctUsers = users.stream()
.distinct(User::getName)
.collect(Collectors.toList());

但是很遗憾, distinct()方法并不能设置条件. 解决方案如下:
首先定义一个过滤器:

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]

MysticalYcc , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Java8 Lambda实现条件去重distinct List
喜欢 (0)
mysticalycc
关于作者:
简短的个人签名

Warning: Attempt to read property "comment_author_email" on null in /www/wwwroot/gschaos.club/wp-content/themes/Git-alpha-6h0SRk/comments.php on line 47
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到