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?

2
  • 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 Commented Jul 26, 2017 at 13:40
  • 1
    you might want to read this question and the one it is marked a duplicate of stackoverflow.com/questions/1992384/… Commented Jul 26, 2017 at 13:45

1 Answer 1

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));
}
Sign up to request clarification or add additional context in comments.

5 Comments

Do i need to cast result Map to HashMap<Integer,Student>?
@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.
@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 stackoverflow.com/questions/29090277/…
@Eran: I was getting Compilation error Type mismatch: cannot convert from Map<Object,Object> to HashMap<Integer,Student>. Now, after casting things are working. Thanks
@Ankit Don't take the result by HashMap<Integer, Student>, take it by Map<Integer, Student>. You don't need any casts then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.