Ranjith Sekar
Ranjith Sekar

Reputation: 1932

Filter a map value using java 8 streams

I have a map as below and wanted to retrieve the values of the inner map using the key.

<bean id="testMap" class="java.util.HashMap">
    <constructor-arg>
      <map>
        <entry key="A" value="AA" />
        <entry key="B">
          <map>
            <entry key="B1" value="B11" />
            <entry key="B2" value="B22" />
            <entry key="B3" value="B33" />
          </map>
        </entry>
      </map>
    </constructor-arg>
  </bean>

below code prints the 1st level, how to print the inner map value?

myMap.entrySet().stream().filter(map -> map.getKey().equals("B")).forEach(p -> System.out.println(p));

Upvotes: 0

Views: 3991

Answers (2)

FrenchTechLead
FrenchTechLead

Reputation: 1146

Can you try this ?
myMap .entrySet().stream() .filter(map -> map.getKey().equals("B")) .values().forEach(value -> System.out.println(value));

Upvotes: 0

Robin Topper
Robin Topper

Reputation: 2345

The answer is less straightforward than the one most people with a nested map are looking for because you have a Map<String,Object>.

Recreating the map you describe:

Map<String,Object> map = new HashMap<>();
Map<String,String> bMap = new HashMap<>();
bMap.put("B1", "B11");
bMap.put("B2", "B22");
bMap.put("B3", "B33");

map.put("A", "AA");
map.put("B", bMap);

Then getting the values of the inner map:

map.entrySet().stream()
   .filter(entry -> entry.getKey().equals("B"))
   .flatMap(entry -> ((Map<String,String>) entry.getValue()).values().stream())
   .forEach(System.out::println);

This prints:

B22
B33
B11

A shorter and faster solution was provided by Holger in the comments:

((Map<String,String>)map.get("B")).values().stream() 
    .forEach(System.out::println);

It does a single lookup of the map entry instead of the linear search in the above solution, i.e. it is faster.

Upvotes: 2

Related Questions