【问题标题】:how to revert a List from a Map when filtering (using streams)过滤时如何从地图中恢复列表(使用流)
【发布时间】:2015-03-31 13:25:50
【问题描述】:

我需要过滤一个 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后,该方法应返回一个包含所有键(匹配值)的列表。

如何处理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>

【问题讨论】:

    标签: java hashmap java-8 java-stream collectors


    【解决方案1】:

    toList 不带任何参数。您可以使用mapEntrys 的Stream 转换为key 的Stream。

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

    【讨论】:

    • 或者,Map.Entry::getKey
    猜你喜欢
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多