Find duplicates in an array list using Map <String, Integer> with input order
Hi everyone, I'm trying to print all duplicated elements, this works fine, but the outputs are out of order (either from user input or from a text file). I want to print all elements in order (duplicates are not printed). How can I do it? Codes from this Find duplicate items in arraylist and display Thanks @Cory Kendall for the codes.
********** updated question: code now works fine with LinkedHashMap. Now I want the outputs printed with number marks (i.e. 1. name1 = 2) gradually. 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 the insertion order on your map, you need to use LinkedHashMap . In your case you should replace
Map<String, Integer> counts = new HashMap<String, Integer>(); with
Map<String, Integer> counts = new LinkedHashMap<String, Integer>(); A LinkedHashMap will keep order.
Map<String, Integer> counts = new LinkedHashMap<String, Integer>(); About LinkedHashMap :
A hash table table and a linked list with a map interface, with a predictable iteration order. This implementation differs from HashMap in that it maintains a doubly linked list passing through all of its entries. This linked list defines the iteration order, which is usually the order in which keys were inserted into the map (Insert Order).
public class FindDup { public static void main(String[] args) { String str[] = { "yogi", "ram", "ram", "yogi", "yogi", "yogi", "raju", "raju", "ram", "yogi", }; Map<String, Integer> map = new HashMap<String, Integer>(); for (String s : str) { if (map.containsKey(s)) { map.put(s, map.get(s) + 1); } else { map.put(s, 1); } } for (Entry<String, Integer> e : map.entrySet()) { System.out.println(e.getKey() + "---" + e.getValue()); } } }