San82 San82 - 1 year ago 73
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 } }

Answer Source

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())));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download