Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an Array to Javaslang Map with counts for each type

Tags:

java

java-8

vavr

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.

like image 692
Ash Avatar asked Mar 01 '17 15:03

Ash


1 Answers

Generally grouping by has another method that takes a Map implementation you are trying to convert to, but it has to be of a type that actually extends java.util.Map:

Collectors.groupingBy(classifier, mapFactory, downstream)

From what I see javaslang.collection.Map is an interface, not an actual implementation.

Since there are no implementations of a javaslang Map that would extend java.util.Map, all you can do is create a custom collector.

Or once already collected to java.util.Map - put those into some instance of javaslang.collection.Map.

like image 52
Eugene Avatar answered Sep 21 '22 13:09

Eugene