Search code examples
functional-programmingvavr

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"))
    );

Solution

  • Not sure if this is the most idiomatic but this is job for foldLeft:

    Stream
       .of(
          Tuple.of("foo", "x"),
          Tuple.of("foo", "y"),
          Tuple.of("bar", "x"),
          Tuple.of("bar", "y"),
          Tuple.of("bar", "z")
       )
       .foldLeft(
          HashMap.empty(), 
          (map, tuple) -> 
             map.put(tuple._1, map.getOrElse(tuple._1, List.empty()).append(tuple._2))
       );