如何使用lambda / Stream api按对象Attribute / Property过滤不同的元素(How to use lambda/Stream api to filter distinc

编程入门 行业动态 更新时间:2024-10-18 03:26:13
如何使用lambda / Stream api按对象Attribute / Property过滤不同的元素(How to use lambda/Stream api to filter distinct elements by object Attribute/Property)

我有一个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.

更多推荐

本文发布于:2023-08-05 23:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1440942.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   元素   对象   api   Stream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!