Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javaslang List of Tuples2 to Map transormation

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"))
    );
like image 670
Ghiro Avatar asked Apr 06 '17 14:04

Ghiro


1 Answers

@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

like image 93
Daniel Dietrich Avatar answered Sep 20 '22 21:09

Daniel Dietrich