我有这个代码:
HashMap<String, Integer> dupeMap = new HashMap<>();
for (String name : sortWords)
if(dupeMap.containsKey(name)) {
int count = dupeMap.get(name);
dupeMap.put(name, ++count);
} else {
dupeMap.put(name, 1);
}
System.out.printf("Duplicates: %s\n", dupeMap.entrySet());
我希望它在遍历我的 ArrayList 后打印出重复项(它是预先创建的,它只是读取给定的文件并按字母顺序对字符串进行排序)。截至目前,它以这种方式打印出重复项:
Duplicates: [Eight=1, Two=2, Seven=2, Four=1]
等有没有一种方法可以成对打印出来(key=value\n key=value 等)并且实际上没有提到唯一的单词?
我对 map 很陌生,所以即使是这段代码我也不得不搜索stackoverflow,虽然我也有同样的想法,但就是想不出一个好的写法。
最佳答案
过滤条目集,去除值为1的元素:
List<Map.Entry<String, Integer>> dupes = dupeMap.entrySet()
.stream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toList());
然后:
System.out.printf("Duplicates: %s\n", dupes);
关于java - 在 Java 中使用 HashMap 打印出重复的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43793283/