大家好,我正在尝试打印所有重复的元素,这工作正常,但输出不按顺序排列(来自用户输入或来自文本文件)。我想按顺序打印所有元素(不打印重复项)。我怎么做?代码来自此Find the duplicate elements in arraylist 并显示 感谢@Cory Kendall 的代码。
**********更新的问题:代码现在与LinkedHashMap完美配合。现在我希望用数字项目符号(即 1. name1 = 2 )递增地打印输出。谢谢
List<String> strings = new ArrayList<String>();
// suppose datas are entered by user incrementally or from a text files.
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String str : strings) {
if (counts.containsKey(str)) {
counts.put(str, counts.get(str) + 1);
} else {
counts.put(str, 1);
}
}
for (Map.Entry<String, Integer> entry : counts.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}