java8 stream distinct by key

2/10/2017来源:ASP.NET技巧人气:1543

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;
}
deviceRecords.stream().filter(distinctByKey(deviceRecord -> deviceRecord.getDeviceMac())).forEach(deviceRecord -> {
    System.out.println(deviceRecord.getDeviceMac());
});