San82 San82 - 3 months ago 10
Java Question

Convert a Collection to Map<String,Collection<String>> using java 8 streams

I am looking to convert a

Collection<Placement>
to
Map<String, Collection<String>>
using java streams, where the
Placement
class is as below

public class Placement {

private String id;

/* Links two placements, may be same for atleast 2 placements. */
private String futureLinkId;
}


The key for the map is future link id and the values are placement ids. For example if there are 2 placements
p1 { id=1, futureLinkId=f1 }, p2 { id=2, futureLinkId=f1 }
, the output should be
Map { f1 - { id1, id2 } }

Answer

This is actually quite simple, despite the convoluted solutions others have offered:

Map<String, List<String>> map = placements.stream()
        .collect(groupingBy(Placement::getFutureLinkId, mapping(Placement::getId, toList())));