javamapreducejava-stream

Java reduce a collection of string to a map of occurence


Consider the a list as id1_f, id2_d, id3_f, id1_g, how can I use stream to get a reduced map in format of <String, Integer>of statistics like:

id1 2
id2 1
id3 1

Note: the key is part before _. Can reduce function help here?


Solution

  • This will get the job done:

    Map<String, Long> map = Stream.of("id1_f", "id2_d", "id3_f", "id1_g")
      .collect(
        Collectors.groupingBy(v -> v.split("_")[0],
        Collectors.counting())
      );