• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Stream流实践(二)list 对象数组根据某字段去重的三种基本思路

武飞扬头像
代码丰
帮助1

前言

相信大家对于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<Student2> list1 = new ArrayList<>();
        List<Student2> list2 = new ArrayList<>();
        for(int i = 1;i<=5;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<=3;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<Student2> resultList = list1.stream()
                .filter(item -> !(list2.stream().map(e -> 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<Student> list = new ArrayList<>();
        for (int i = 1; i <= 5; 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<Student> after = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getId))), ArrayList::new));
    }
}
学新通

方法三:concurrentHashMap的putIfAbsent Stream流

/**
 * 去重工具类
 * @author 代码丰
 */
@Slf4j
public 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 <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

/**
 * @author: 代码丰
 * @Date: 2022/10/24 17:24
 * @Description:
 */
public class DeRepeatFromOneListTest {
    public static void main(String[] args) {

        //测试3:去重一个列表的重复值
        List<Student> list = new ArrayList<>();

        for(int i = 1;i<=5;i  ){
            Student student = new Student();
            student.setId("1");
            student.setIndex("1" String.valueOf(i));
            student.setName("name" String.valueOf(i));
            list.add(student);
        }
        
        List<Student> after= list.stream().filter(CustomizeDistinctUtil.distinctByKey(Student::getId)).collect(Collectors.toList());
    }
}
学新通

尾巴

大家学废了吗?

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgbkaeb
系列文章
更多 icon
同类精品
更多 icon
继续加载