我有一个Object List 。 每个对象都有一个带有名为“xyz”的键的地图。 我希望列表中的元素具有该特定键的唯一值。
我知道我们可以使用set / map轻松完成这项工作,但我特别关注lambda解决方案。
我认为这会奏效。
list.stream() .filter(distinctByXyz(f -> f.getMap.get("xyz"))) .collect(Collectors.toList()));我有一个功能来区分它们
private <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; }问题是过滤器内部的函数f.getMap()是无效的。 显示编译错误(无法解析方法)
I have a List of Object. Every object has a map with a key named "xyz". I want elements in the list which has unique value to that particular key.
I know we can do this easily with set/map but I'm particularly looking for lambda solution.
I thought this would work.
list.stream() .filter(distinctByXyz(f -> f.getMap.get("xyz"))) .collect(Collectors.toList()));I've a function to distinct them
private <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; }The problem is the function f.getMap() inside filter isnt working. Showing compilation error (Cannot resolve method)
最满意答案
您的代码中似乎有一些拼写错误,这应该有效:
list .stream() .filter(distinctByKey(f -> f.getMap().get("xyz"))) .collect(Collectors.toList());当它应该是distinctByXyz时,你正在使用distinctByKey 。 然后f.getMap应该是f.getMap() ,你的括号稍微偏离。
You seem to have a few typos in your code, this should work:
list .stream() .filter(distinctByKey(f -> f.getMap().get("xyz"))) .collect(Collectors.toList());You are using distinctByXyz when it should really be distinctByKey. Then f.getMap that should probably be f.getMap() and also you are slightly off with your parenthesis.
更多推荐
发布评论