Package Cn.php;import Java.util.arraylist;import Java.util.arrays;import java.util.collections;import Java.util.comparator;import Java.util.hashmap;import Java.util.hashset;import Java.util.LinkedHashMap;import Java.util.list;import java.util.map;import Java.util.map.entry;import Java.util.set;public class CountList {public static void Main (string[] args) {list<string> STRs = Arrays.aslist ("A", "B", "C", "D", "E", "a", "a", "a", "a", "B", "B", "B"); map<string, integer> map = new hashmap<string, integer> (); set<string> set = new hashset<string> (STRs); for (string str:set) {for (string lstr:strs) {if (Str.equals (l STR) {if (Map.containskey (str)) {Integer count = map.get (str); Count++;map.put (str, count);} else {map.put (str, 1);}}} Printmap (map); map<string, integer> sortmap = sortmapbyvalue (map);p rintmap (SORTMAP);} private static map<string,integer> Sortmapbyvalue (map<string, integer> Map) {list<map.entry<string , Integer>> Maplist = new arraylist<map.entry<string, integer>> (Map.entryset ()); Collections.sort (maplist, New comparator<map.entry<string, integer>> () {@Overridepublic int compare ( Entry<string, integer> o1,entry<string, integer> O2) {return o1.getvalue ()-o2.getvalue ();}); map<string,integer> result = new linkedhashmap<string,integer> (); for (map.entry<string, Integer> Entry:maplist) {result.put (Entry.getkey (), Entry.getvalue ());} return result;} public static void Printmap (Map<string, integer> Map) {for (map.entry<string, integer> Entry:map.entrySet () {System.out.println ("Key:" + entry.getkey () + "Value:" + entry.getvalue ());}}}
Public map<string, String> Sortmapbykey (map<string, string> orimap) {if (Orimap = null | | orimap.isempty ()) { return null;} map<string, string> sortedmap = new treemap<string, string> (new comparator<string> () {public int Compare (String Key1, String key2) {int intKey1 = 0, IntKey2 = 0;try {intKey1 = GetInt (key1); intKey2 = GetInt (Key2);} catch (Exception e) {intKey1 = 0;intkey2 = 0;} return intkey1-intkey2;}}); Sortedmap.putall (Orimap); return sortedmap;} private int getInt (String str) {int i = 0;try {Pattern p = pattern.compile ("^\\d+"); Matcher m = p.matcher (str), if (M.find ()) {i = integer.valueof (M.group ());}} catch (NumberFormatException e) {e.printstacktrace ();} return i;}
The number of occurrences of elements in the Java statistics List and the ordering of the map by key or key value