java使用Stream取出重复的值、去重和统计数量

关于Stream的详解可以看这篇文章

使用Steam取出重复的值、去重的代码示例如下:

当list中存入的元素为String时:

@Test
public void test06() {
    List<String> telephoneList = new ArrayList<>();
    telephoneList.add("123456");
    telephoneList.add("123456");
    telephoneList.add("235466");
    telephoneList.add("789456");
    telephoneList.add("235466");

    System.out.println("======================取出重复的字符串=========================");
    //取出重复的字符串
    List<String> repeatList = telephoneList.stream().collect(Collectors.groupingBy(e -> e, Collectors.counting()))
            .entrySet().stream().filter(e -> e.getValue() > 1)
            .map(Map.Entry::getKey).collect(Collectors.toList());
    System.out.println(repeatList);//[123456, 235466]

    //分解上述的各步骤
    Map<String, Long> collect = telephoneList.stream().collect(Collectors.groupingBy(str -> str, Collectors.counting()));
    System.out.println(collect);//{123456=2, 789456=1, 235466=2}
    Set<Map.Entry<String, Long>> entries = collect.entrySet();
    System.out.println(collect.entrySet());//[123456=2, 789456=1, 235466=2]

    System.out.println("======================去重字符串=========================");
    //去重字符串方法1
    Set<String> strings = telephoneList.stream().collect(Collectors.toSet());
    System.out.println(strings);//[123456, 789456, 235466]
    //去重字符串方法2
    List<String> list = telephoneList.stream().distinct().collect(Collectors.toList());
    System.out.println(list);//[123456, 235466, 789456]
}

当list中存入的元素为对象时:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private int id;
    private String name;
    private String pwd;
    private int num;
}
@Test
public void test07() {
    List<User> list = new ArrayList<>();
    list.add(new User(1, "xiaoming", "123456", 4));
    list.add(new User(2, "xiaoming", "123", 5));
    list.add(new User(3, "xiaohong", "234", 6));
    list.add(new User(4, "xiaobai", "245", 7));

    //根据name去重,取出重复值
    List<String> collect = list.stream().collect(Collectors.groupingBy(User::getName, Collectors.counting()))
            .entrySet().stream().filter(e -> e.getValue() > 1)
            .map(Map.Entry::getKey).collect(Collectors.toList());
    System.out.println(collect);//[xiaoming]

    int sum = list.stream().mapToInt(User::getNum).sum();
    System.out.println(sum);//22
}

参考:java8 list取出重复值、统计数量 – cchilei – 博客园

    原文作者:IamaMartian
    原文地址: https://blog.csdn.net/qq_41644069/article/details/121577569
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞