行业知识
Stream流实践(二):list 对象数组根据某字段去重的三种基本思路
2026-12-06 14:14:17
来源:互联网转载
前言
相信大家对于list简单数组的去重很熟悉了,例如以下代码
()int[] arrays = {1, 2, 2, 2, 3, 3, 3}; Arrays.stream(arrays).distinct().forEach(item -> { System.out.println("item ->" + item); }); 那我们来探讨下,对于list中保存为对象的数组,根据内部对象的某一个字段去重有什么好的思路呢?
给出一个简单的Student对象
()public class Student { String id; String index; String name;} 针对该Student对象,以下是我想到的三种方法去重方法
方法一:List.contains + Stream流
/** * @author: 代码丰 * @Date: 2022/10/24 13:57 * @Description: */public class DeRepeatFromTwoListTest { public static void main(String[] args) { //测试1:去重两个列表的重复值 填充参数 List list1 = new ArrayList(); List list2 = new ArrayList(); for(int i = 1;i Student2 Student2 = new Student2(); Student2.setId(String.valueOf(i)); Student2.setIndex(String.valueOf(i)); Student2.setName("name"+String.valueOf(i)); list1.add(Student2); } for(int i = 1;i Student2 Student2 = new Student2(); Student2.setId(String.valueOf(i)); Student2.setIndex(String.valueOf(i)); Student2.setName("name"+String.valueOf(i)); list2.add(Student2); } // 基本思路: // 1、将【数组流】转换为【字段流】 // 2、流重新恢复数组 // 3、然后再使用List.contains方法去过滤 List e.getId()).collect(Collectors.toList()).contains(item.getId())) ).collect(Collectors.toList()); System.out.println(resultList); }} 方法二:Set不可重复特性 + Stream流
/** * @author: 代码丰 * @Date: 2022/10/24 17:24 * @Description: */public class DeRepeatFromThreeListTest { public static void main(String[] args) { //测试2:去重一个列表的重复值 List list = new ArrayList(); for (int i = 1; i Student student = new Student(); student.setId("1"); student.setIndex("1" + String.valueOf(i)); student.setName("name" + String.valueOf(i)); list.add(student); } //基本思路:利用set不可重复key特性 List new TreeSet(Comparator.comparing(Student::getId))), ArrayList::new)); }} 方法三:concurrentHashMap的putIfAbsent + Stream流
/** * 去重工具类 * @author 代码丰 */@Slf4jpublic class CustomizeDistinctUtil { //基本思路 //1.利用 ConcurrentHashMap 的 putIfAbsent(假如map中key对应的value不存在,放value进入map 假如map中key对应的value存在,返回key对应的value) //2. 构造 Predicate 返回值 // 不存在时,putIfAbsent 得到null,== null比较后 会返回true //3. filter true的得到保留 false的直接过滤 //4. 效果为只有不存在的才会保留,存在的都得到了过滤,即实现去重 public static Predicate distinctByKey(Function
上一篇:蓝鲸加速服务器怎么用?