Java How to sort the map (use of the map collection) _java

Source: Internet
Author: User

Today's statistics need to be sorted by region code (AREACODE) for the area of the x-axis, because the map used to build the XMLData data statistics, so the map needs to be sorted in the statistical process.

A brief introduction of map

Before we explain the map sort, let's take a little more information about the map. Map is the set interface of key value pairs, and its implementation classes mainly include: Hashmap,treemap,hashtable and Linkedhashmap. The difference between the four is as follows (brief introduction):

HashMap: Our most commonly used map, which stores data according to the key's hashcode value, can get its value directly according to key, and it has fast access speed. HashMap allows only one record of the key value to be null (more than one will overwrite); The value of multiple records is allowed to be null. is not synchronized.

TreeMap: The records that can be saved are sorted according to key, the default is sorted in ascending order, or you can specify a comparator for sorting, and when you traverse TreeMap with iterator, the record is ordered. TreeMap does not allow the value of key to be null. is not synchronized.

Hashtable: Similar to HashMap, the difference is that the value of key and value is not allowed to be null; it supports thread synchronization, which means that only one thread can write Hashtable at any one time, and it also causes Hashtale to be slower when writing.

Linkedhashmap: Save the Insertion Order of the records, and when traversing linkedhashmap with iterator, the first record must be inserted first. It's slower than hashmap when traversing. Both the key and value are allowed to be null, not synchronized.

Ii. map Sequencing

TreeMap

TreeMap default is ascending, and if we need to change the sort, we need to use the comparer: Comparator.

A comparer interface that comparator the collection object or array can be sorted by implementing the public compare (T O1,to2) method of the interface, which is mainly based on the first parameter O1, which returns a negative integer, 0, or a positive integer, respectively, less than, equal to, or greater than O2. As follows:

Copy Code code as follows:

public class Treemaptest {
public static void Main (string[] args) {
map<string, string> map = new treemap<string, string> (
New Comparator<string> () {
public int Compare (string obj1, String obj2) {
Descending sort
Return Obj2.compareto (OBJ1);
}
});
Map.put ("C", "CCCCC");
Map.put ("A", "AAAAA");
Map.put ("B", "bbbbb");
Map.put ("D", "ddddd");

Set<string> keyset = Map.keyset ();
Iterator<string> iter = Keyset.iterator ();
while (Iter.hasnext ()) {
String key = Iter.next ();
SYSTEM.OUT.PRINTLN (key + ":" + map.get (key));
}
}
}

The results of the operation are as follows:

D:ddddd
C:ccccc
b:bbbbb
A:aaaaa

The above example is sorted according to the key value of the treemap, but sometimes we need to sort according to the value of TreeMap. To order value we need to use the collections sort (list<t> list, comparator<, Super t> C) method, which sorts the specified list according to the order in which the comparer is produced. But there is a prerequisite that all elements must be able to be compared according to the comparator provided. As follows:

Copy Code code as follows:

public class Treemaptest {
public static void Main (string[] args) {
map<string, string> map = new treemap<string, string> ();
Map.put ("D", "ddddd");
Map.put ("B", "bbbbb");
Map.put ("A", "AAAAA");
Map.put ("C", "CCCCC");

Here, convert Map.entryset () to list
list<map.entry<string,string>> list = new Arraylist<map.entry<string,string>> (map.entrySet ());
And then sort through the comparer.
Collections.sort (list,new comparator<map.entry<string,string>> () {
Ascending sort
public int Compare (entry<string, string> O1,
Entry<string, string> O2) {
Return O1.getvalue (). CompareTo (O2.getvalue ());
}

});

for (map.entry<string,string> mapping:list) {
System.out.println (Mapping.getkey () + ":" +mapping.getvalue ());
}
}
}


Run results

A:aaaaa
b:bbbbb
C:ccccc
D:ddddd

HashMap

We are HashMap value is not in order, he is according to the hashcode of key to achieve. How are we going to implement the sort of hashmap for this disorder? Referring to the TreeMap value sort, we can also implement the HashMap sort.

Copy Code code as follows:

public class Hashmaptest {
public static void Main (string[] args) {
map<string, string> map = new hashmap<string, string> ();
Map.put ("C", "CCCCC");
Map.put ("A", "AAAAA");
Map.put ("B", "bbbbb");
Map.put ("D", "ddddd");

list<map.entry<string,string>> list = new Arraylist<map.entry<string,string>> (map.entrySet ());
Collections.sort (list,new comparator<map.entry<string,string>> () {
Ascending sort
public int Compare (entry<string, string> O1,
Entry<string, string> O2) {
Return O1.getvalue (). CompareTo (O2.getvalue ());
}

});

for (map.entry<string,string> mapping:list) {
System.out.println (Mapping.getkey () + ":" +mapping.getvalue ());
}
}
}

Run results

A:aaaaa
b:bbbbb
C:ccccc
D:ddddd

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.