public static void main(String[] args) throws IOException {
User user = new User();
user.setAge(10);
user.setName("aa");
User user1 = new User();
user1.setAge(10);
user1.setName("bb");
User user2 = new User();
user2.setAge(10);
user2.setName("bb");
List<User> list = new ArrayList<>();
list.add(user);
list.add(user1);
list.add(user2);
// filter()入参不可以直接输入true 或者 false
list.stream().filter(distinctByKey(a -> a.getName())).forEach(e -> System.out.println(e.toString()));
// Map<Object,Boolean> seen = new ConcurrentHashMap<>();
// Boolean a = seen.putIfAbsent("a", true);
// System.out.println(a == null);
// Boolean b = seen.putIfAbsent("a", true);
// System.out.println(b == null);
}
/**
* 实现通过对象属性来判断对象是否重复
* 给stream().filter()作入参使用
* @param keyExtractor
* @param <T>
* @return
*/
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
// 给一个属性作map的key
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
// 通过putIfAbsent方法判断该key是否存在 如果存在则返回value 不存在返回null
// 当为true时 则证明该属性为当前唯一 后面再有相同的属性进来就会为false 则filter会将该条数据过滤
// 以此实现过滤重复数据
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
class User{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}