Java流缩减为映射

问题描述 投票:-8回答:1

我有字符串数组列表,如何将它们简化为哈希图

输入:[a, b, a, a, c, x]

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

PS。我搜索了这个。我需要使用reduce而不是像其他问题中那样进行频率计数,因为我的问题是简化的实际任务。

java java-stream
1个回答
0
投票

感谢@HadiJ回答

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;
    }
);
© www.soinside.com 2019 - 2024. All rights reserved.