stream筛选出集合中对象属性重复值

stream筛选出集合中对象属性重复值

字符串集合筛选
		List<String> strings = Arrays.asList("a", "bb", "cc", "aa", "bb", "dd", "cc");
        List<String> result = new ArrayList<>();
        Map<String, Long> collect = strings.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        collect.forEach((k,v)->{
            if(v>1)
                result.add(k);
        });
        System.out.println(result.toString());
另一种写法,无需创建收集结果的List集合
		List<String> strings = Arrays.asList("a", "bb", "cc", "aa", "bb", "dd", "cc");
        Map<String, Long> collect = strings.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<String> result = collect.entrySet().stream()
        					.filter(e -> e.getValue() > 1).map(Map.Entry::getKey)
        					.collect(Collectors.toList());
        System.out.println(result.toString());

结果:

[cc, bb]
对象集合筛选

对象:

public class User {

    private String userName;

    private String password;

    private Integer age;

    public User(String userName, String password, Integer age) {
        this.userName = userName;
        this.password = password;
        this.age = age;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

对userName属性筛选:

		List<User> users = new ArrayList<>();
        users.add(new User("xpf1","1238",18));
        users.add(new User("xpf2","1234",18));
        users.add(new User("xpf3","1235",18));
        users.add(new User("xpf","1236",18));
        users.add(new User("xpf","1237",18));
        Map<String, Long> collect = users
                .stream()
                .map(User::getUserName)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<String> result = new ArrayList<>();
        collect.forEach((k,v)->{
            if(v>1)
                result.add(k);
        });
        System.out.println(result.toString());

结果:

[xpf]
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zarathusa

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值