Home > Back-end >  The Map key sorting and converted to Json
The Map key sorting and converted to Json

Time:11-04

Public static void main (String [] args) {

List List=new ArrayList<> (a);
//User entity test String id, name;
//the current test id to grouping, specific please click development scenarios to modify
List. The add (new City (1, "Beijing", "Beijing"));
List. The add (new City (2, "Shanghai", "Shanghai"));
List. The add (new City (3, "chongqing", "chongqing"));
List. The add (new City (4, "according to", "changsha"));
List. The add (new City (5, "shenyang", "shenyang"));
List. The add (new City (6, "tieling", "tieling"));
List. The add (new City (7, "working", "nanjing"));

//initialize a map
Map The map=new HashMap<> (a);
//traverse the List
For (City City: List) {
//get to the city whole pinyin
String key=city. GetFirstalphabet ();
//get pinyin initials
String subs=key. The substring (0, 1);
If (map. Either containsKey (subs)) {
//the map of this id as the key, the data stored in the current key map
The map. The get (subs). The add (city);
} else {
//the map does not exist in a id as the key, the new key used to store data
List The userList=new ArrayList<> (a);
The userList. Add (city);
The map. The put (subs, userList);
}
}
System.out.println(map);
}

The current output is as follows:
{b=[} {code=1, city=Beijing], s=[={code=2, city Shanghai}, {code=5, city shenyang}=], c=[={code=3, city of chongqing}, {} code=4, city=changsha], t=[{code=6, city=tieling}], n=[} {code=7, city=nanjing]}

Looking forward to the output:
{b=[} {code=1, city=Beijing], c=[={code=3, city of chongqing}, {} code=4, city=changsha], n=[} {code=7, city=nanjing], s=[={code=2, city Shanghai}, {code=5, shenyang city=}], t=[] {code=6, city=tieling}}

Output is sorted by alphabet, best can convert the result to the Json format, is there any great god help me the code, thank you very much,

CodePudding user response:



  • Related