1.java.util.Set--无重复元素集合类
2.add方法--向Set集合中添加对象
语法 boolean add(E e)
参数:e是要添加到Set集合中的对象.
返回值:如果Set集合中不包含要添加的对象,则添加对象并返回true;如果已经包含相同的对象,则不改变Set集合,并返回false.
3.举例:
List<String> userNames=new ArrayList<String>();
userNames.add("zhangsan");
userNames.add("list");
userNames.add("zhangsan");
if(CollectionUtils.isNotEmpty(userNames)){
Set<String> unRepeatNames=new HashSet<String>();
for (String userName: userNames) {
boolean isRepeat=unRepeatNames.add(userName);
if(!isRepeat){
System.out.println("重复用户名:"+userName);
}
}
}
4.如果需要对List中的对象User进行去重,需要重写User的equals方法和hashCode方法
@Data
public class User implements Serializable {
private Long id;
private String userName;
private String mobile;
private int age;
@Override
public boolean equals(Object o){
User entity = (User)o;
//用户名和手机号相同时默认为同义用户
if (entity !=null && Stringutils.isNotEmpty(entity.userName()) && Stringutils.isNotEmpty(entity.mobile)
&& entity.getUserName().equals( this.userName) && entity.getMobile() == this.mobile){
return true;
}
return false;
}
@Override
public int hashCode(){
return 1;
}
public Long getId(){
return this.id;
}
public void setId(Long id){
this.id = id;
}
public String getUserName(){
return userName;
}
public void setUserName(String userName){
this.userName = userName;
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = age;
}
public String getMobile(){
return this.mobile;
}
public void setMobile(String mobile){
this.mobile = mobile;
}
}