在java stream中实现去重有多种方法,具体取决于需求和场景。以下是常见的几种方法及示例:
1. 使用 distinct() 方法
适用于对象已正确实现 equals()
和 hashcode()
,基于对象整体去重并保留顺序:
list<person> uniquepersons = persons.stream() .distinct() .collect(collectors.tolist());
2. 根据对象的属性去重
方法一:使用 collectors.tomap
根据属性作为键,保留第一个或最后一个元素,支持顺序(使用 linkedhashmap
):
// 保留第一个出现的元素 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
适用于并行流,但可能不保留顺序:
// 并行流去重(不保证顺序) 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
分组后取每组的第一个元素,保持顺序:
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. 根据字符串长度去重示例
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 来记录已经出现过的元素,然后过滤掉重复的元素。
//定义一个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);
附:java中使用stream流根据对象中的某一字段进行去重
在开发中经常会遇到数据去重的,单个基本类型的集合去重比较容易,比如string、integer,直接使用流中的distinct方法去重即可。但是遇到对象集合,需要使用对象中的某个字段去重就不能使用这个方法了。可以在流式编程中加入treeset,treeset是一个有序且不重复的有序集合。以用户user数据位列:
list<user> list = userservice.list(); list.stream().collect(collectors.collectingandthen(collectors.tocollection(() -> new treeset<>(comparator.comparing( f -> f.getdeptname()+":"+f.getstatus()))),arraylist::new));
这里是根据用户的部门以及用户的状态进行数据去重,将用户的部门以及状态拼接位一个字符串进行去重,这样stream内部会将整个user集合数据组装成这样进行整体去重,这样去重下来的数据就是,每一个部门中只会存在一个状态的部门人员数据,这里是举个例子,在实际环境中,你可以将user换成自己想要去重的实体集合。
总结
distinct()
:简单高效,适用于对象整体去重。tomap
或groupingby
:灵活,支持按属性去重,可控制保留顺序。filter
+set
:适合并行流,但需注意线程安全和顺序问题。
根据具体场景选择最合适的方法,确保代码简洁且性能良好。
到此这篇关于java stream去重常见的多种方法及示例的文章就介绍到这了,更多相关java stream去重方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论