第一种方法:.distinct()(只适用于基本类型)
List<Integer> intList = new ArrayList<>();
List<Integer> collect = intList
.stream()
.distinct().collect(Collectors.toList());
注意:如果想用distinct对对象集合去重,也不是不可以,需要重写对象的equals()和 hashCode()
放在文末
第一种方法:(适用于根据对象的某个属性去重)
List<User> intList = new ArrayList<>();
List<User> collect = userList.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(User::getUserId))), ArrayList::new));
扩展:利用 distinct 对对象集合去重
public class User {
private String name;
private Integer age;
@Override
public boolean equals(Object obj) {
if (obj instanceof User) {
User user = (User) obj;
return (age.equals(user.age));
}
return super.equals(obj);
}
@Override
public int hashCode() {
int result = 17;
result = result * 31 + age.hashCode();
result = result * 31 + age;
return result;
}
}
List<User> intList = new ArrayList<>();
List<User> collect = intList
.stream()
.distinct().collect(Collectors.toList());