java - Map a Stream<T> to a Map<T, Long> that is counting? -
i have stream<t>, possible generate map<t, long> increases count 1 every element? i'd if reverse t, long long, t, before storing in map, example input/output:
example contents of stream<string>:
kgj def dgh wanted output first question:
(kgj, 1) (def, 2) (dgh, 3) wanted output in end:
(1, kgj) (2, def) (3, dgh) what have far, stream<vertexdata>:
primitives.stream() .flatmap(primitive -> primitive.getvertexdata().stream()) .distinct() .collect(collectors.groupingby(i -> i, collectors.counting())) .foreach((k, v) -> system.out.println("k = " + k + " / v = " + v)); this turns stream<primitive> stream<vertexdata> distinct elements, , map<vertexdata, long> counts occurences, not want, want keep on counting @ every element passes.
is there way ask?
what can write own collector counting on elements encountered. following works:
stream<string> strings = stream.of("kgj", "def", "dgh"); strings.distinct().collect(collector.of( hashmap::new, (biconsumer<map<string, long>, string>) (map, str) -> { map.put(str, long.valueof(map.size() + 1)); }, (left, right) -> { long s = left.size(); right.entryset().foreach(e -> left.put(e.getkey(), long.valueof( e.getvalue() .longvalue() + s))); return left; })).foreach((k, v) -> system.out.println("k = " + k + " / v = " + v)); note (somewhat complex) combiner (third argument collector.of() needed in cases stream processed in parallel).
Comments
Post a Comment