1 /**2 3 * Requirements: Number of occurrences of each character in the statistics string4 * 5 * Analysis:6 * 1, define a string that needs to be counted7 * 2, converts a string to a character array8 * 3, defines the double-column collection, stores the characters in the string and the number of occurrences of the character9 * 4, iterate through the character array to get each character, and store the characters in a double-column collectionTen * 5, in the stored procedure to make a judgment, if the collection does not contain this key, the character as a key, a value of 1 storage, if the collection contains this key, the value is added 1 storage One * 6, print double-column collection Gets the number of occurrences of a character A */ -public staticvoidMain (string[] args) { - //1, defines a string that needs to be counted as a character theString s = "AAAABBBBBCCCCCCCCCCCCC"; - //2, converting a string to a character array - Char[] arr =S.tochararray (); - //3, define a double-column collection that stores the characters in the string and the number of occurrences of the character +Hashmap<character, integer> HM =NewHashmap<>(); - //4. Iterate through the character array to get each character and store the characters in a double-column collection + for(CharC:arr) { A //5, the stored procedure to make a judgment, if the collection does not contain this key, the character as a key, the value of 1 storage, if the collection contains this key, the value is added 1 storage at /*if (!hm.containskey (c)) {//If this key is not included - Hm.put (c, 1); - }else { - Hm.put (c, Hm.get (c) + 1); - }*/ -Hm.put (c,!hm.containskey (c)? 1:hm.get (c) + 1); in } - //6, print double-column collection Gets the number of occurrences of a character to + for(Character Key:hm.keySet ()) {//Hm.keyset () represents the collection of all keys -SYSTEM.OUT.PRINTLN (key + "=" + hm.get (key));//hm.get (key) Gets the value based on the key the } *}
Hashmap<student, string> hm88 =NewHashmap<>(); HashMap<student, string> hm99 =NewHashmap<>();
Hm88.put (...) ... HashMapNewHashmap<>(); Hm.put (Hm88,Methyl); Hm.put (Hm99,Ethyl); //traversing a double-column collection for(Hashmap<student, String> h:hm.keyset ()) {//Hm.keyset () represents a collection of keys in a double-column collectionString value = Hm.get (h);//Get (h) Gets the value object based on the key object//double-column collection object that iterates through a key for(Student Key:h.keyset ()) {//H.keyset () Gets the total of all student key objects in the collectionString value2 =H.get (key); SYSTEM.OUT.PRINTLN (Key+ "=" + value2 + "=" +value); } }
Java Linkedhashmap,treemap,hashmap