8

I was trying to filter Entries in HashMap using Streams API, but stuck in last method call Collectors.toMap. So, I don't have clue to implemement toMap method

    public void filterStudents(Map<Integer, Student> studentsMap){
            HashMap<Integer, Student> filteredStudentsMap = studentsMap.entrySet().stream().
            filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi")).
            collect(Collectors.toMap(k , v));
    }

public class Student {

        private int id;

        private String firstName;

        private String lastName;

        private String address;
    ...

    }

Any Suggestions?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
Ankit
  • 2,126
  • 4
  • 33
  • 53
  • 2
    Just so you're clear. Each parameter in Collectors.toMap takes a Function, so k and v don't exist. It would be `toMap(s -> s.getKey(), s -> s.getValue())` which can be converted to Method References as in the answer by @Eran. Which I recommend even if they are a little longer – Novaterata Jul 26 '17 at 13:40
  • 1
    you might want to read this question and the one it is marked a duplicate of https://stackoverflow.com/questions/1992384/program-to-an-interface-what-does-it-mean – Novaterata Jul 26 '17 at 13:45

1 Answers1

16

Just generate the output Map out of the key and value of the entries that pass your filter:

public void filterStudents(Map<Integer, Student> studentsMap){
    Map<Integer, Student> filteredStudentsMap = 
        studentsMap.entrySet()
                   .stream()
                   .filter(s -> s.getValue().getAddress().equalsIgnoreCase("delhi"))
                   .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Do i need to cast result Map to `HashMap`? – Ankit Jul 26 '17 at 13:40
  • 1
    @Ankit Are you asking whether the result would be a HashMap, or are you asking how to make sure the result is a HashMap? The 2 argument variant of `Collectors.toMap` returns a `Map`. There are other variants in which you can specify the type of Map you want created. – Eran Jul 26 '17 at 13:42
  • 2
    @Ankit You want to use the simplest Interface that that is necessary. It shouldn't matter if it's a HashMap (which it will be), but if you need a specific implementation like LinkedHashMap, then you need to use the 4 param toMap https://stackoverflow.com/questions/29090277/streams-collections-tomap-from-list-how-to-keep-the-order – Novaterata Jul 26 '17 at 13:42
  • @Eran: I was getting Compilation error `Type mismatch: cannot convert from Map to HashMap`. Now, after casting things are working. Thanks – Ankit Jul 26 '17 at 13:49
  • @Ankit Don't take the result by HashMap, take it by Map. You don't need any casts then. – Jagannath Jul 27 '17 at 01:24