What is the most idiomatic way to transform a Stream<Tuple2<T,U>>
into a Map<T,List<U>>
with javaslang 2.1.0-alpha?
// initial stream
Stream.of(
Tuple.of("foo", "x"),
Tuple.of("foo", "y"),
Tuple.of("bar", "x"),
Tuple.of("bar", "y"),
Tuple.of("bar", "z")
)
should become:
// end result
HashMap.ofEntries(
Tuple.of("foo", List.of("x","y")),
Tuple.of("bar", List.of("x","y","z"))
);
@Opal is right, foldLeft is the way to go in order to create a HashMap from Tuples.
In javaslang 2.1.0-alpha we additionally have Multimap to represent Tuples in a Map-like data structure.
// = HashMultimap[List]((foo, x), (foo, y), (bar, x), (bar, y), (bar, z))
Multimap<String, String> map =
HashMultimap.withSeq().ofEntries(
Tuple.of("foo", "x"),
Tuple.of("foo", "y"),
Tuple.of("bar", "x"),
Tuple.of("bar", "y"),
Tuple.of("bar", "z")
);
// = Some(List(x, y))
map.get("foo");
(See also HashMultimap Javadoc)
Depending on how the map is further processed, this might come in handy.
Disclaimer: I'm the creator of Javaslang
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With