This article demonstrates how to use collections.frequency and map to calculate the number of occurrences of a duplicate item. (Collections.frequency is supported after JDK version 1.5)
Package Com.qiyadeng.core;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.HashMap;
Import Java.util.HashSet;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Set;
Import Java.util.TreeMap; public class Countduplicatedlist {public static void main (string[] args) {List List = new Arrayl
IST ();
List.add ("a");
List.add ("B");
List.add ("C");
List.add ("D");
List.add ("B");
List.add ("C");
List.add ("a");
List.add ("a");
List.add ("a");
System.out.println ("\ n Example 1-Calculates the number of ' a ' occurrences");
System.out.println ("A:" + collections.frequency (list, "a"));
System.out.println ("\ n Example 2-calculates the number of occurrences of all objects");
Set uniqueset = new HashSet (list);
for (String temp:uniqueset) {System.out.println (temp + ":" + collections.frequency (list, temp));
} System.out.println ("\ n Example 3-the number of occurrences of the object is computed with a map"); Map map = new HashMap ();
for (String temp:list) {Integer count = map.get (temp);
Map.put (temp, (count = = null)? 1:count + 1);
} printmap (map);
System.out.println ("\nmap sort-Sort by key");
Map TreeMap = new TreeMap (map);
Printmap (TREEMAP); public static void Printmap (map map) {for (Map.entry Entry:map.entrySet ()) {System.out
. println ("Key-value:" + entry.getkey () + "-" + entry.getvalue ()); }
}
}
Output results
Example 1-Calculates the number of ' a ' occurrences
a:4
Example 2-Calculates the number of occurrences of all objects
d:1
b:2
c:2
a:4
Example 3-Calculates the number of occurrences of an object with a map
Key-valu e:d-1
key-value:b-2
key-value:c-2
key-value:a-4
Map sort-sorted by key
key-value:a-4
key -value:b-2
key-value:c-2
key-value:d-1
Source: http://www.qiyadeng.com/