How to filter documents from map based on 2 values and create another map

I am not much familiar with the java 8 syntax and its stream API, And trying to achieve some complex filtering on map of map.

Below is my code using the traditional map looping and filtering.

public class HashMapFilter {

    public static void main(String[] args) {
        HashMap<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();

        Map<String,String> foo = new HashMap<>();
        foo.put("lang", "en");
        foo.put("type", "msg");
        foo.put("location", "usa");
        map.put("1", foo);

        Map<String,String> bar = new HashMap<>();
        bar.put("lang", "en");
        bar.put("type", "user");
        bar.put("location", "usa");
        map.put("2", bar);

        Map<String,String> baz = new HashMap<>();
        baz.put("lang", "en");
        baz.put("type", "msg");
        baz.put("location", "usa");
        map.put("3", baz);

        HashMap<String, Map<String, String>> filteredMap = new HashMap<String, Map<String, String>>();

        for(Map.Entry<String, Map<String, String>> entry : map.entrySet()) {
            Map<String, String> innerMap = entry.getValue();
            if(innerMap.get("lang").equals("en") && innerMap.get("type").equals("msg")) {
                filteredMap.put(entry.getKey(),innerMap);
            }
        }

        System.out.println("Size of filtered map : "+ filteredMap.size());
    }
}

As you can see I just want to filter the inner maps on the basis of lang and type but code using the traditional way is quite complex and I am sure, it can easily be rewritten using the java 8 stream API.
Note: As illustrated in my example after the filtered map would contains only 2 inner map, as there is only 2 maps which has both lang=en and type=msg.

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

It is almost same just add that condition in filter and then use Collectors.toMap for collecting into Map Map<String, Map<String, String>> filteredMap = map.entrySet() .stream() .filter(entry->entry.getValue().get("lang").equals("en") && entry.getValue().get("type").equals("msg")) .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));