Find duplicate items in arraylist and display

Can someone help me? I need to write a program where I have 10 elements in an arraylist , and I need to find the number of duplicate values ​​that it has, and count and display the values ​​as hello.

Example: let's say I have

 list = {"stack", "overflow", "stack", "yahoo", "google", "msn", "MSN", "stack", "overflow", "user" } 

The result should be:

 stack = 3 overflow = 2 google = 1 msn = 2 yahoo =1 user = 1 
+3
source share
6 answers

Use the Google Guava MultiSet library . It supports adding multiple elements and counting the number of occurrences of each element in a multiset.

 Multiset<String> wordsMultiset = HashMultiset.create(); wordsMultiset.addAll(words); for(Multiset.Entry<String> entry : wordsMultiset.entrySet() ){ System.out.println("Word : "+entry.getElement()+" count -> "+entry.getCount()); } 
+5
source

Use a HashMap. Here is a simple implementation

 List<String> strings = new ArrayList<String>(); strings.put("stack", "overflow", "stack", "yahoo", "google", "msn", "MSN", "stack", "overflow", "user"); 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()); } 
+5
source

use hashmap
eg:

 Map<String, Integer> occurrencies = new HashMap<String, Integer>(); for (String word : list) { occurrencies.put(word, occurrencies.containsKey(word) ? occurrencies.get(word) + 1 : 1); } for (Entry<String, Integer> entry : occurrencies.entrySet()) { System.out.println("Word: "+entry.getKey() + ", occurences: "+entry.getValue()); } 
+3
source
 Map<String, Integer> frequency = new HashMap<String, Integer>(); for (String element : list) { if (frequency.contains(element)) { frequency.put(element, frequency.get(element) + 1); } else { frequency.put(element, 1); } } for (Map.Entry<String, Integer> entry : frequency.entrySet()) { System.out.print(entry.getKey() + " = " + entry.getValue() + " "); } System.out.println(); 
+2
source

Use HashMap

 Map<String, Integer> freqMap = new HashMap<String, Integer>(); 
+1
source

Create a Map<String, Integer> , and then iterate over the ArrayList .

Then for each item: -

  • If it is already on the map, increase the Integer value for this element by 1
  • If it is missing, add this element with an initial Integer value of 1
+1
source

All Articles