List<String> strList=new ArrayList<>(Arrays.asList("张三","李四","李四","王五"));
Set<String> strSet=new HashSet<>(strList);
if (strList.size() == strSet.size()) {
System.out.println("没有重复");
} else {
System.out.println("重复了,老铁");
}
List<String> strList=new ArrayList<>(Arrays.asList("张三","李四","李四","王五"));
long count = strList.stream().distinct().count();
if (strList.size() == count) {
System.out.println("没有重复");
} else {
System.out.println("重复了,老铁");
}
User类:
@Data
public class User {
private Long id;
private String name;
private Integer age;
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public User() {
}
}
判断User集合中name是否有重复:
List<User> users = new ArrayList<User>(){
{
add(new User(13131l,"张三",33));
add(new User(21244l,"李四",23));
add(new User(31865l,"王五",41));
add(new User(31231l,"大聪明",25));
add(new User(31123l,"大智慧",27));
add(new User(38751l,"张三",30));
}
};
List<String> names = users.stream().map(User::getName).collect(Collectors.toList());
System.out.println(names.toString());
//distinct()过滤重复的姓名 count()计算数量
long count = names.stream().distinct().count();
System.out.println("去重后的个数:"+count);
if (names.size() == count){
System.out.println("没有重复");
}else {
System.out.println("重复了,老铁");
}
原文:https://www.cnblogs.com/netu/p/14818685.html