Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 retrieve Map's values into an array with stream and filter

Would someone help me with getting the array of the map values with stream and filtering?

public class TheMap extends HashMap<String, String> {
    public TheMap(String name, String title) {
        super.put("name", name);
        super.put("title", title);
    }

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

        map.put(0L, null);
        map.put(1L, new TheMap("jane", "engineer"));
        map.put(2L, new TheMap("john", "engineer"));
        map.put(3L, new TheMap(null, "manager"));
        map.put(4L, new TheMap("who", null));
        map.put(5L, new TheMap(null, null));
    }
}

The result that I am looking for is an ArrayList<TheMap> with only these two entries:

TheMap("jane", "engineer")
TheMap("john", "engineer")

Basically, retrieve TheMap with none-null name and title.

like image 936
TX T Avatar asked Apr 04 '17 20:04

TX T


2 Answers

List<Map<String, String>> list = 
        map.values().stream().filter(v -> 
                              v != null && 
                              !v.entrySet().isEmpty() &&
                              !v.containsValue(null)).
        collect(Collectors.toList());
like image 114
Sébastien Temprado Avatar answered Nov 20 '22 14:11

Sébastien Temprado


If you need an arrayList of TheMap, try the following way:

ArrayList<TheMap> as = map.values()
   .stream()
   .filter(v -> v != null && v.get("name") != null && v.get("title") != null)
   .map(m -> (TheMap)m)
   .collect(Collectors.toCollection(ArrayList::new)));
like image 3
VHS Avatar answered Nov 20 '22 16:11

VHS