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]