Hi everyone I am trying to print all the duplicated elements, this works fine but the outputs are not in order (either from user input or from the text file).
I want to print all elements with order (duplicates are not printed). How do I do that?
The codes are from this Find the duplicate elements in arraylist and display
Thanks @Cory Kendall for the codes.
**********updated question: the code now works perfect with LinkedHashMap. Now I want the outputs to be printed with number bullets (ie, 1. name1 = 2 ) incrementally. Thanks
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());
}
If you want to remember insertion order in your Map, you need to use
LinkedHashMap. In your case you have to replacewith