Java 数组去重

JAVA中List对象去除重复值,大致分为两种情况,一种是List、List这类,直接根据List中的值进行去重

List listStr = Arrays.asList("a", "b", "c", "a","a");
List filltrList = listStr.stream().distinct().collect(Collectors.toList());

另一种是List这种,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 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 collect = list.stream().distinct().collect(Collectors.toList());

你可能感兴趣的:(Java 数组去重)