Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 471
Holger Hahn Avatar asked Jan 24 '26 11:01

Holger Hahn


1 Answers

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());
}
like image 189
Eran Avatar answered Jan 26 '26 01:01

Eran