San82 San82 - 10 months ago 31
Java Question

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

I am looking to convert a

Map<String, Collection<String>>
using java streams, where the
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 } }


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

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