public List<XYZ> getFilteredList(List<XYZ> l1) {
return l1
.stream()
.filter(distinctByKey(XYZ::getName))
.filter(distinctByKey(XYZ::getPrice))
.collect(Collectors.toList());
}
private 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;
}有人能帮帮我吗?这句话的意思是什么?>
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
为什么lambda的结果与null相比?
发布于 2022-06-10 12:53:23
你的问题涉及以下几个方面:
return t -> seen.putIfAbsent(keyExtractor.apply(t),
Boolean.TRUE) == null;e.g. XYZ::getName)putIfAbsent将创建的地图通过seen引用为closure,即使映射本身已经超出了范围。keyExtractor将通过提供的设置器检索示例中的键(无论名称还是价格),方法引用seen试图将布尔值true添加到提供的键的映射中(在本例中,从keyExtractor检索name和price )。如果键已经存在,它将返回该值,即true。因为true不等于null,所以返回false,并且过滤器不传递值。如果值不存在,则返回null。由于null == null是真的,所以将返回true并通过过滤器传递值(也就是说,它是非常不同的)。这是一个如何工作的例子。这使用了一个简单的记录,并且只对名称应用了一个过滤器。
record XYZ(String getName, String other){
@Override
public String toString() {
return String.format("[name=%s, other=%s]", getName, other);
}
}
public static void main(String[] args) {
List<XYZ> l1 = List.of(
new XYZ("A","B"),
new XYZ("B","B"),
new XYZ("B","C"),
new XYZ("B","D"),
new XYZ("C","B"));
Object ob =
l1.stream().filter(distinctByKey(XYZ::getName))
.collect(Collectors.toList());
System.out.println(ob);
}版画
[[name=A, other=B], [name=B, other=B], [name=C, other=B]]请注意,通过过滤器只允许使用B的名称,其他的则被阻塞。
private 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;
}https://stackoverflow.com/questions/72571561
复制相似问题