distinctByKey
重点是最后的方法 自己写一个distinctByKey
package com.hyq.learning;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Queues;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* @author dibulidohu
* @classname Tetst
* @date 2019/4/2420:32
* @description
*/
public class Tetst {
public static void main(String[] args) {
Tetst tetst = new Tetst();
tetst.doex();
}
public void doex() {
List<User> users = Lists.newArrayList();
users.add(new User(1,25));
users.add(new User(2,45));
users.add(new User(3,32));
users.add(new User(3,12));
users.add(new User(3,33));
List<User> collect = users.stream().filter(distinctByKey(User::getId)).collect(Collectors.toList());
for (User user : collect) {
System.out.println(user.toString());
}
}
class User {
private Integer id;
private Integer age;
public User(Integer id, Integer age) {
this.id = id;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> map = new ConcurrentHashMap<>();
return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}