Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter Map in Java 8 Streams

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?

like image 304
Ankit Avatar asked Jul 26 '17 13:07

Ankit


People also ask

How do you filter a stream map?

Since our filter condition requires an int variable we first need to convert Stream of String to Stream of Integer. That's why we called the map() function first. Once we have the Stream of Integer, we can apply maths to find out even numbers. We passed that condition to the filter method.

Can we use filter and map together in Java 8?

Once we have the Stream of Integer, we can apply maths to find the even numbers. We passed that condition to filter method. If we needed to filter on String, e.g. select all string which has length > 2, then we would have called filter before map. That's all about how to use map and filter in Java 8.

How do I filter a map based on values in Java 8?

We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.

What is difference between map and filter in Java stream?

Filter takes a predicate as an argument so basically you are validating your input/collection against a condition, whereas a map allows you to define or use a existing function on the stream eg you can apply String. toUpperCase(...) etc. and transform your inputlist accordingly.


1 Answers

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));
}
like image 196
Eran Avatar answered Oct 12 '22 21:10

Eran