Converting an array to a Javaslang Map with counts for each type

I am currently browsing the Javaslang library and I am trying to convert part of my code to Javaslang.

I currently have this bit of code, which is completely pure Java

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

I was looking to convert this to Javaslang since I am interested in the library and I just wanted to play with it.

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

I have tried this so far, but then I am stuck because I cannot convert it.

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

So, I have a list of Cell objects, but I'm trying to figure out how to convert it to javaslang.collection.Map

* EDIT *

I looked at getting my original java.util.Map on javaslang.collections.Hashmap with this

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

Javaslang, .

+6
3

: Javaslang.

Javaslang :

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

Array Map javaslang.collection.

, Array Seq Set.

+2

, , , , java.util.Map:

Collectors.groupingBy(classifier, mapFactory, downstream)

, javaslang.collection.Map, , .

javaslang Map, java.util.Map, , , .

java.util.Map - javaslang.collection.Map.

+4

, Eugene , : - .

: Javaslang , Javaslang, . , Javaslang HashMap:

javaslang.collection.HashMap:: collector()

public static < K, V > Collector < Tuple2 < K, V > , ArrayList < Tuple2 < K, V → , HashMap < K, V → collector()

, Stream.collect(java.util.stream.Collector) HashMap.

:

K -

V -

A HashMap Collector.

Edit: , , , , , :

  • Tuple<K,V>
  • ArrayList<Tuple2<K,V>>
  • , , "", ArrayList HashMap.

, Stream<Cell>, . : , Javaslang Javaslang Map ( , HashMap). , Java Javaslang, :

javaslang.collection.HashMap:: ofAll (java.util.Map)

HashMap java.util.Map.

, :

Stream<Cell> cells // <- you have this

cells.collect(
  collectingAndThen(
    groupingBy(Function.identity(), counting()),
    HashMap::ofAll
  )
);

java.util.stream.Collectors.

Java Map, , java Map Javaslang.

Note. I don't have Javaslang, and I can't check if the code snippet compiles above, but it looks like it does what you want.

+3
source

Source: https://habr.com/ru/post/1015375/


All Articles