Search code examples
functional-programmingvavr

Extract keys and left values from a Map<?, Either> in Javaslang


Given a Map<String, Either<Boolean, Integer>, what's the most straightforward way to convert it to a Map<String, Boolean> containing only the entries with boolean values?

Right now I have this:

Map<String, Boolean> boolMap = eitherMap
  .filter(entry -> entry._2.isLeft())
  .map((key, value) -> Tuple.of(key, value.getLeft())
;

This works, but seems unnecessarily wordy, and it seems like there should be some tighter, one-step, “flatmap that 💩” solution.


Solution

  • Disclaimer: I'm the creator of Javaslang

    Here is a solution based on javaslang-2.1.0-alpha. We take advantage of the fact that Either is right-biased. Because we focus on the left values, we swap the Either. The flatMap iterates then over the Either, if it contains a boolean.

        import javaslang.collection.Map;
        import javaslang.control.Either;
    
        import static javaslang.API.*;
    
        public class Test {
    
            public static void main(String[] args) {
    
                Map<String, Either<Boolean, Integer>> map = Map(
                        "a", Left(true),
                        "b", Right(1),
                        "c", Left(false));
    
                Map<String, Boolean> result =
                        map.flatMap((s, e) -> e.swap().map(b -> Tuple(s, b)));
    
                // = HashMap((a, true), (c, false))
                println(result);
    
            }
        }
    

    You achieve the same in javaslang-2.0.5 by using static factory methods like Tuple.of(s, b).