Search code examples
javajava-stream

Java stream reduce to map


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.


Solution

  • 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;
            }
        );