Holger Hahn
Holger Hahn

Reputation: 33

how to revert a List from a Map when filtering (using streams)

I need to filter a HashMap

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

for some of its values and have a method

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

The method shall return a List with all the keys (matching values) after filtering the Map.

How to deal with the collect()? I get an error message

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>

Upvotes: 3

Views: 751

Answers (1)

Eran
Eran

Reputation: 394126

toList doesn't take any parameters. You can use map to convert the Stream of Entrys to a Stream of the keys.

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

Upvotes: 3

Related Questions