Below java code example shows how to count duplicate
elements in a list by using Collection.frequency and
Map collection.
Code:
---------------------------------CountDuplicate.java------------------------------------------------------------
import java.util.ArrayList;
import
java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class CountDuplicate {
public static void main(String[] args) {
List<String>
items = new ArrayList<>();
items.add("Zero");
items.add("One");
items.add("Two");
items.add("Two");
items.add("Two");
items.add("Two");
items.add("Three");
items.add("four");
items.add("five");
items.add("five");
items.add("five");
System.out.println("count
elements by usin frequency");
// counting an
element in a list by using frequency
int countedItem = Collections.frequency(items, "five");
System.out.println(countedItem);
System.out.println("");
System.out.println("count by
using set");
System.out.println("");
// count all
elements which are in list
HashSet<String>
itemsSet = new
HashSet<String>(items);
for (String element : itemsSet) {
System.out.println(element + "'s in list :
" +
Collections.frequency(items, element));
}
System.out.println("");
System.out.println("count
elements by using map");
System.out.println("");
// count number of
elements occurance in list by using map
Map<String,
Integer> countingMap = new HashMap<String, Integer>();
for (String element : itemsSet) {
Integer
eleCount = countingMap.get(element);
countingMap.put(element, (eleCount == null) ? 1 : eleCount + 1);
}
for
(Map.Entry<String, Integer> elementEntry : countingMap.entrySet()) {
System.out.println(elementEntry.getKey() + "'s in list
" +
elementEntry.getValue());
}
}
}
Output:
----------------------------------------------------------
count elements by usin frequency
3
count by using set
Zero's in list : 1
four's in list : 1
One's in list : 1
Two's in list : 4
five's in list : 3
Three's in list : 1
count elements by using map
Zero's in list 1
four's in list 1
One's in list 1
Two's in list 1
five's in list 1
Three's in list 1
No comments:
Post a Comment