Stream流Filter

自定义指定字段进行过滤

  1. 工具类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public class StreamUtils {  
    /**
    * 使用对象指定属性进行预测,返回一个预测器
    * @param keyExtractor 对象属性
    * @return Predicate
    * @param <T> class类
    */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Map<Object,Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }}
  2. 使用方法
    1
    xxxEntity.stream().filter(StreamUtils.distinctByKey(xxxEntity::getXxxx)).tiList();