javaslang List of Tuples2 to Map transormation
Asked Answered
E

2

7

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"))
    );
Eligibility answered 6/4, 2017 at 14:27 Comment(0)
I
6

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))
   );
Intercalary answered 6/4, 2017 at 17:56 Comment(1)
I am learning the API, and missed the fold operations. ThanksEligibility
E
10

@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

Elielia answered 6/4, 2017 at 22:36 Comment(2)
Now I know there's another tool in the toolbox. Thanks and congrats on the great library so far.Eligibility
Thank you, at your service!Elielia
I
6

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))
   );
Intercalary answered 6/4, 2017 at 17:56 Comment(1)
I am learning the API, and missed the fold operations. ThanksEligibility

© 2022 - 2024 — McMap. All rights reserved.