本文实例为大家分享了Java中Stream流去除List重复元素的具体代码,供大家参考,具体内容如下
业务场景
在开发中我们常常需要过滤List中的重复对象,而重复的定义往往是根据单个条件或者多个条件,如果是单个条件的话还是比较好处理的,即使不使用工具,代码也可以很容易实现,但如果判断依据不是单个条件,而是多个条件的话,代码实现起来就会比较复杂,此时我们一般就会使用工具来简化开发
单条件去重代码
1 2 3 4 |
ArrayList<listData> collect = list.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator测试数据paring( listData::getId))), ArrayList:: new )); |
解释
list-列表
listData-列表中存的对象
id是判断是否重复的条件,只保留唯一id对象
多条件去重代码
1 2 3 |
ArrayList<listData> collect = list.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator测试数据paring(p->p.getPatentName() + ";" + p.getLevel()))), ArrayList:: new )); |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import java.util.*; import java.util.stream.Collectors;
public class ExcelUtil {
private static String[] params = { "p001" , "p002" , "p003" , "p004" };
public static void main(String[] args) {
List<Datum> dataList = new ArrayList<>();
for ( int i = 0 ; i < 100 ; i++) { if (i% 2 == 0 ){ Datum datum = new Datum( params[ new Random().nextInt(params.length)], params[ new Random().nextInt(params.length)], params[ new Random().nextInt(params.length)], params[ new Random().nextInt(params.length)], params[ new Random().nextInt(params.length)] ); dataList.add(datum); } }
System.out.println( "0 size : " +dataList.size()+ " -> " +dataList);
// 单条件 ArrayList<Datum> collect1 = dataList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<Datum>( Comparator测试数据paring( Datum::getId))), ArrayList:: new ));
System.out.println( "1 size : " +collect1.size()+ " -> " +collect1);
// 两个条件 ArrayList<Datum> collect2 = dataList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator测试数据paring(p->p.getId() + ";" + p.getAddress()))), ArrayList:: new ));
System.out.println( "2 size : " +collect2.size()+ " -> " +collect2);
// 三个条件 ArrayList<Datum> collect3 = dataList.stream().collect(Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<>( Comparator测试数据paring(p->p.getInfo() + ";" + p.getAddress()+ ";" +p.getName()))), ArrayList:: new ));
System.out.println( "3 size : " +collect3.size()+ " -> " +collect3);
}
} |
效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
原文链接:https://blog.csdn.net/weixin_41405524/article/details/120717488
查看更多关于Java中Stream流去除List重复元素的方法的详细内容...