Map<String, Set<Pathway>> conversion to Map of string to set of one of Pathways properties

Viewed 42

I have a pathway object like this:

class Pathway {
  private dbId;
  private name;
}

These pathways are on a map structure of gene, to a set of all the pathways the gene belongs in

Map<String, Set<Pathway>> geneToPathwayList;

I want to convert this into a map of Map<String, Set<String>> geneToPathwayDbId using streams.

So to do this, I am attempting to iterate over the entry set of the map, collect the keys as the keys, and then collect the values by mapping the set of Pathways to a set of dbIds but I can't get the syntax right. Here is how it currently looks:

Map<String, Set<String>> finalMap = 
    geneToPathwayList.entrySet().stream()
    .collect(Collectors.toMap(
        Map.Entry::getKey, 
            e -> e.stream().map(Pathway::getStId).collect(Collectors.toSet())));

I am hung up on how to select e as the value from each entry.

Any help in solving this would be greatly helpful!

2 Answers

sounds like you're after

e -> e.getValue().stream().map(Pathway::getDbId).collect(Collectors.toSet())

An alternative using for each

Map<String,Set<String>> finalMap = new HashMap<>();
   geneToPathwayList.forEach((k,v)-> 
           finalMap.put(k, v.stream().map(Pathway::getDbId).collect(Collectors.toSet())));
Related