用Set判断List是否有重复值

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值