russell
russell

Reputation: 165

How to get all values from the inner maps of a map using a common key?

I have a map of maps: HashMap<String, Map<DistinctCode, String>>.

I need to extract the String value from the inner maps just by using a DistinctCode. How can I do that in one line or statement?

In other words, I need a method something like this:

mapOfMap.find(distinctcode)

Is it doable in one line or statement?

Upvotes: 2

Views: 3070

Answers (4)

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13773

A slightly different Java 8 approach without null filtering:

final Set<String> values = mapOfMaps.values().stream()
            .filter(m -> m.containsKey(distinctCode))
            .map(m -> m.get(distinctCode))
            .collect(Collectors.toSet()); //this can be simplified using a static import

Upvotes: 0

Paul Boddington
Paul Boddington

Reputation: 37645

With Java 8 you can do

Set<String> strings = mapOfMaps.values().stream()
           .map(m -> m.get(distinctCode))
           .filter(v -> v != null)
           .collect(Collectors.toSet());

Upvotes: 2

Syam S
Syam S

Reputation: 8499

In Java 8

List<String> list = map.values().stream().map(m -> m.get(distinctcode)).filter(Objects::nonNull).collect(Collectors.toList());

Upvotes: 4

laune
laune

Reputation: 31290

DistinctCode dv = ...;

Stream<String> res = 
    mom.values().stream().map(p->p.get(dv)).filter(p->p!=null);

Upvotes: 0

Related Questions