Java 数组去重
2022-09-06 本文已影响0人
赵哥窟
JAVA中List对象去除重复值,大致分为两种情况,一种是List<String>、List<Integer>这类,直接根据List中的值进行去重
List<String> listStr = Arrays.asList("a", "b", "c", "a","a");
List<String> filltrList = listStr.stream().distinct().collect(Collectors.toList());
另一种是List<User>这种,List中存的是javabean对象,需要根据List中对象的某个值或某几个值进行比较去重。需要重写对象的equals和hashCode
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String username;
private String sex;
private LocalDate birthday;
private String address;
private String password;
private Integer orgId;
@Override
public boolean equals(Object obj) {
if(this == obj){
return true;//地址相等
}
if(obj == null){
return false;//非空性:对于任意非空引用x,x.equals(null)应该返回false。
}
if(obj instanceof User){
User user = (User) obj;
//需要比较的字段相等,则这两个对象相等
if(this.username.equals(user.getUsername())){
return true;
}
}
return false;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (username == null ? 0 : username.hashCode());
return result;
}
}
List<User> list = new ArrayList<>();
User u1 = new User();
u1.setId(1);
u1.setUsername("张三");
list.add(u1);
User u2 = new User();
u2.setId(1);
u2.setUsername("张三");
list.add(u2);
User u3 = new User();
u3.setId(1);
u3.setUsername("张三");
list.add(u3);
List<User> collect = list.stream().distinct().collect(Collectors.toList());