Java Stream 去重的多种方法

在Java Stream中实现去重有多种方法,具体取决于需求和场景。以下是常见的几种方法及示例:

1. 使用 distinct() 方法

适用于对象已正确实现 equals()hashCode(),基于对象整体去重并保留顺序:

java 复制代码
List<Person> uniquePersons = persons.stream()
                                    .distinct()
                                    .collect(Collectors.toList());

2. 根据对象的属性去重

方法一:使用 Collectors.toMap

根据属性作为键,保留第一个或最后一个元素,支持顺序(使用 LinkedHashMap):

java 复制代码
// 保留第一个出现的元素
List<Person> uniqueByName = persons.stream()
    .collect(Collectors.toMap(
        Person::getName,
        Function.identity(),
        (oldP, newP) -> oldP, // 保留旧值(第一个)
        LinkedHashMap::new    // 保持插入顺序
    ))
    .values().stream()
    .collect(Collectors.toList());

// 保留最后一个出现的元素
List<Person> uniqueByNameLast = persons.stream()
    .collect(Collectors.toMap(
        Person::getName,
        Function.identity(),
        (oldP, newP) -> newP  // 保留新值(最后一个)
    ))
    .values().stream()
    .collect(Collectors.toList());
方法二:使用 filter 和线程安全的 Set

适用于并行流,但可能不保留顺序:

java 复制代码
// 并行流去重(不保证顺序)
Set<String> seen = ConcurrentHashMap.newKeySet();
List<Person> uniqueByName = persons.parallelStream()
    .filter(p -> seen.add(p.getName()))
    .collect(Collectors.toList());

// 顺序流去重(保留顺序)
Set<String> seenOrdered = new HashSet<>();
List<Person> uniqueByNameOrdered = persons.stream()
    .filter(p -> seenOrdered.add(p.getName()))
    .collect(Collectors.toList());
方法三:使用 groupingBy

分组后取每组的第一个元素,保持顺序:

java 复制代码
List<Person> uniqueByName = persons.stream()
    .collect(Collectors.groupingBy(
        Person::getName,
        LinkedHashMap::new,    // 保持插入顺序
        Collectors.toList()
    ))
    .values().stream()
    .map(group -> group.get(0)) // 取第一个元素
    .collect(Collectors.toList());

3. 根据字符串长度去重示例

java 复制代码
List<String> words = Arrays.asList("apple", "banana", "orange", "grape", "kiwi");
List<String> uniqueByLength = words.stream()
    .collect(Collectors.toMap(
        String::length,
        Function.identity(),
        (oldVal, newVal) -> oldVal,
        LinkedHashMap::new
    ))
    .values().stream()
    .collect(Collectors.toList());
// 结果: ["apple", "banana", "kiwi"](保留顺序)

4. 自定义去重借助Filter 实现:

自定义一个 Predicate 函数,用一个 Set 来记录已经出现过的元素,然后过滤掉重复的元素。

java 复制代码
//定义一个Predicate函数
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> sets = ConcurrentHashMap.newKeySet();
    return t -> sets.add(keyExtractor.apply(t));
}

//根据age属性去重
list.stream().filter(distinctByKey(s -> s.getAge()))
        .forEach(System.out::println);

总结

  • distinct():简单高效,适用于对象整体去重。
  • toMapgroupingBy:灵活,支持按属性去重,可控制保留顺序。
  • filter + Set:适合并行流,但需注意线程安全和顺序问题。

根据具体场景选择最合适的方法,确保代码简洁且性能良好。

相关推荐
找不到、了19 分钟前
有关SOA和SpringCloud的区别
java·spring·spring cloud
等等54320 分钟前
Java EE初阶——初识多线程
java·开发语言·jvm
hrrrrb22 分钟前
【Rust】枚举和模式匹配
开发语言·rust
小白学大数据30 分钟前
Python爬虫中time.sleep()与动态加载的配合使用
爬虫·python·scrapy·数据分析
沐雨潇竹33 分钟前
使用定时器监视当前PID 如果当前程序关闭 UI_Core.exe 也随之自动关闭实现方法
开发语言·qt·ui
小饕39 分钟前
LangChain构建大模型应用之问答系统(五)
人工智能·python·langchain
大锦终40 分钟前
【C++】红黑树
c语言·开发语言·数据结构·c++
星霜旅人1 小时前
Java并发编程
java
David Bates1 小时前
代码随想录第41天:图论2(岛屿系列)
python·算法·图论
是代码侠呀1 小时前
让Promise飞,让github star 飞
python·开源·github·github star·github 加星