java - 过滤时如何从 map 中恢复列表(使用流)

标签 java hashmap java-8 java-stream collectors

我需要过滤一个HashMap

Map<String, Point> points = new HashMap<String, Point>();

对于它的一些值并有一个方法

public List<String> getEqualPointList(Point point) {
    return this.points.entrySet().stream().filter(p -> p.getValue().isEqual(point)).collect(Collectors.toList(p -> p.getKey()));
}

该方法将在过滤Map后返回一个包含所有键(匹配值)的List。

如何处理collect()?我收到一条错误消息

Multiple markers at this line
- The method toList() in the type Collectors is not applicable for the arguments 
  ((<no type> p) -> {})
- Type mismatch: cannot convert from Collection<Map.Entry<String,Point>> to
  List<String>

最佳答案

toList 不接受任何参数。您可以使用 mapEntry 流转换为 key 流。

public List<String> getEqualPointList(Point point) {
    return this.points
               .entrySet()
               .stream()
               .filter(p -> p.getValue().isEqual(point))
               .map(e -> e.getKey())
               .collect(Collectors.toList());
}

关于java - 过滤时如何从 map 中恢复列表(使用流),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263518/

相关文章:

Java lambda 返回一个 lambda

java - 当标记 android studio 触发时,如何获取我保存在 firebase 中的数据 latlng

java - HashMap 的元素顺序错误

java - 避免具有不同行数的动态表行流向 XWPFDocument(Apache POI) 中的不同页面

java - 两个或多个(哈希)映射的联合

java - 使用大小为 30K 的数组进行测试时,使用 HashMap 实现的代码失败

java - 多个字段上的对象列表分组 Java 8

java - 按类别划分 java 流

java - Wicket DropDownChoice 不能与 PropertyModels 一起正常工作

java - 如何向 Canvas 元素添加上下文菜单?