-1

I got array list of strings, how could I reduce them to hash map

Input: [a, b, a, a, c, x]

Output: {(a: 3), (b: 1), (c: 1), (x: 1)}

PS. I searched for this. I need to do that with reduce not with frequency counting as in other questions, because my question is a simplified real task.

halfer
  • 19,824
  • 17
  • 99
  • 186
Егор Лебедев
  • 1,161
  • 1
  • 10
  • 26

1 Answers1

9

Thanks @HadiJ for answer

Map<String,Integer> result = Arrays.stream(str)
    .reduce(new HashMap<>(), (hashMap, e) -> {
        hashMap.merge(e, 1, Integer::sum);
        return hashMap;
    },
    (m, m2) -> {
        m.putAll(m2);
        return m;
    }
);
Егор Лебедев
  • 1,161
  • 1
  • 10
  • 26