Search code examples
javajava-8vavr

Converting an Array to Javaslang Map with counts for each type


I am currently looking at Javaslang library and I am trying to convert some of my code to Javaslang.

I currently have this bit of code which is all pure Java

Cell[][] maze; //from input
Map<Cell, Long> cellCounts = Stream.of(maze)
            .flatMap(Stream::of)
            .collect(groupingBy(c -> c, counting()));

I was looking at converting this to Javaslang, as I am interested in the library and I just wanted to play around with it.

I am trying to do a similar thing, but convert to a Javaslang map instead of the java.util.Map.

I have tried this so far but then I am getting stuck as I cant see a way of converting it.

Array.of(maze)
     .flatMap(Array::of)

So I have my list of Cell objects, but I am trying to figure out how to convert this to a javaslang.collection.Map

*EDIT *

I have looked at getting my original java.util.Map to a javaslang.collections.Hashmap by this

HashMap<Cell, Long> cellsCount = HashMap.ofEntries(cellCounts
                                                        .entrySet()
                                                        .toArray(new Map.Entry[0]));

This still doesnt seem to be in line with Javaslang, but I will keep looking.


Solution

  • Disclaimer: I'm the author of Javaslang.

    This simplest way to achieve it with Javaslang is the following:

        Map<Cell, Integer> cellCounts = Array.of(maze)
                .flatMap(Array::of)
                .groupBy(c -> c)
                .mapValues(Array::length);
    

    Here Array and Map are imported from javaslang.collection.

    Please note that you can substitute Array with any other Seq or Set implementation.