Set去重会用到
List的remove(obj)方法也会用到
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Organ other = (Organ) obj;
if(id.equals(other.getId())) {
return true;
}
return false;
}
@Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}
stream去重
@Test
public void listDistinctByStreamDistinct() {
// 1. 对于 String 列表去重
List<String> stringList = new ArrayList<String>() {{
add("A");
add("A");
add("B");
add("B");
add("C");
}};
//去重
stringList = stringList.stream().distinct().collect(Collectors.toList());
}
对象去重需要重写hashCode和equals方法
@Test
public void listDistinctByStreamDistinct() throws JsonProcessingException {
// 1. 对于 Student 列表去重
List<Student> studentList = getStudentList();
studentList = studentList.stream().distinct().collect(Collectors.toList());
}
根据对象属性字段去重, 借助filter.
定义方法返回函数式接口Predicate , 参数是函数式接口 Function
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
@Test
public void distinctByPropertyTest() throws JsonProcessingException {
List<Student> studentList = getStudentList();
studentList = studentList.stream().filter(distinctByKey(Student::getName)).collect(Collectors.toList());
}