Package com.xiawei.sort;
Import java.util.ArrayList;
Import java.util.Collections;
Import Java.util.Comparator;
Import Java.util.HashMap;
Import java.util.List;
Import Java.util.Map;
Import Java.util.Map.Entry;
public class TestString {
Requires that characters in a string be sorted from small to large by character occurrences
Idea: 1. Converts a string into an array of characters in the form of a single character;
2.for iterates through this character array, and each character is stored as a key in the map collection using the ContainsKey () method, and the number of occurrences of each character is stored as a value in the collection;
3. When traversing the deposit, it is necessary to determine whether the key (character) exists, if there is the value of the key +1, no, the key is stored, and the value of the key is 1 times;
4. Define a list to stipulate its generics as map.entry;
6. Obtain each key-value by EntrySet () and add it to the list collection;
7. Rewrite the Compare () method and sort by the collections sort () method;
8. Finally traverse the list to print;
public static void Main (string[] args) {
String str = "Adasfsxsdfadgdfgajxgdafsydfyfgddaxsa";
To get a character array by using the ToCharArray () method
char[] chr = Str.tochararray ();
Define a Map collection
map<character,integer> map = new hashmap<> ();
Iterate over this character array
for (char cha:chr) {
if (Map.containskey (cha)) {
Map.put (Cha, map.get (cha) +1);//value value +1
}else{
Map.put (CHA, 1);
}
}
Take a look at the map collection
SYSTEM.OUT.PRINTLN (map);
Define a list
list<map.entry<character,integer>> list = new arraylist<> ();
Each key-value is then added to the list collection by EntrySet () [EntrySet (): Returns the Set view (Key-value) of the mappings contained in this map;
List.addall (Map.entryset ());
Collections.sort (list, new Comparator<map.entry<character, integer>> () {
@Override
public int Compare (Entry<character, integer> O1, Entry<character, integer> O2) {
Return O1.getvalue ()-o2.getvalue ();//From small to large sort
}
});
Traversing list Printing
System.out.println ("Ascending order:");
int a=0;
for (map.entry<character,integer> listsort:list) {
if (A < List.size ()-1) {
System.out.print (Listsort.getkey () + ",");
}else{
System.out.print (Listsort.getkey ());
}
a++;
}
}
}
Requires that characters in a string be sorted from small to large by character occurrences