3 回答
TA贡献1809条经验 获得超8个赞
在下面测试了Stuart的功能,它看起来很棒。下面的操作在每个字符串的第一个字母上有所区别。我要弄清楚的唯一部分是ConcurrentHashMap如何仅维护整个流的一个实例
public class DistinctByKey {
public static <T> Predicate<T> distinctByKey(Function<? super T,Object> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
public static void main(String[] args) {
final ImmutableList<String> arpts = ImmutableList.of("ABQ","ALB","CHI","CUN","PHX","PUJ","BWI");
arpts.stream().filter(distinctByKey(f -> f.substring(0,1))).forEach(s -> System.out.println(s));
}
输出是...
ABQ
CHI
PHX
BWI
TA贡献1811条经验 获得超5个赞
您或多或少必须要做类似的事情
elements.stream()
.collect(Collectors.toMap(
obj -> extractKey(obj),
obj -> obj,
(first, second) -> first
// pick the first if multiple values have the same key
)).values().stream();
添加回答
举报