Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream over nested HashMap with condition

Let's assume that we have some Map structere like below:

Map<Type, Map<String, String>> outterMap = new HashMap<>();
Map<String, String> innerMap1 = new HashMap<>();

innerMap1.put("1", "test1");
innerMap1.put("2", "test2");
innerMap1.put("3", "test3");
innerMap1.put("4", "test4");

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

innerMap2.put("5", "test5");
innerMap2.put("6", "test6");
innerMap2.put("3", "test7");

outterMap.put(Type.TEXT, innerMap1);
outterMap.put(Type.INTEGER, innerMap2);

and we would like to print all values from innerMap with assigned Type enum. With foreach loop it would look like this:

for (Type type : outterMap.keySet()) {
    for (String value : outterMap.get(type).values()) {
        if(type.equals(Type.TEXT)) {
            System.out.println("TEXT: " + value);
        }else if(type.equals(Type.INTEGER)) {
            System.out.println("INTEGER: " + value);
        }
    }
}

So the output on console would looks like this:

TEXT: test1
TEXT: test2
TEXT: test3
TEXT: test4
INTEGER: test7
INTEGER: test5
INTEGER: test6

Is there any option to write it with help of the streams. I was able to use stream with lambda, and it looks like this:

outterMap.keySet().stream().forEach(type -> {
            outterMap.get(type)
            .values()
            .stream()
            .forEach(value -> {
                if(type.equals(Type.TEXT)) {
                    System.out.println("TEXT: " + value);
                } else if (type.equals(Type.INTEGER)) {
                    System.out.println("INTEGER: " + value);
                }
            });
        });
like image 807
Suule Avatar asked Nov 24 '25 04:11

Suule


1 Answers

Probably this:

outterMap.keySet()
         .stream()
         .flatMap(x -> outterMap.getOrDefault(x, Collections.emptyMap())
                                .values()
                                .stream()
                                .map(y -> new SimpleEntry<>(x, y)))
         .forEachOrdered(entry -> {
               System.out.println(entry.getKey() + "  " + entry.getValue());
         });

But this is by far less readable than what you have.

like image 195
Eugene Avatar answered Nov 26 '25 19:11

Eugene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!