How to sort map in Java (use of map collection)

Source: Internet
Author: User

When doing statistics today, you need to sort the x-axis regions according to the region code (AREACODE), and you need to sort the map in the statistical process because the map used in the XMLData is built for data statistics.

First, Brief introduction map

Before we get to the map sort, let's start with a little bit about map. Map is a set interface of key-value pairs, and its implementation classes mainly include: Hashmap,treemap,hashtable and Linkedhashmap. The differences between the four are as follows (brief introduction):

HashMap: Our most commonly used map, which stores data based on the hashcode value of a key, can get its value directly based on key, and it has fast access speed. HashMap allows a maximum of one record's key value to be null (multiple entries are overwritten), and the value to allow multiple records is null. is not synchronized.

TreeMap: The ability to sort its saved records according to key, by default is sorted in ascending order, you can also specify a sort of comparator, when using iterator traversal TreeMap, the resulting records are sorted out. TreeMap does not allow the value of key to be null. is not synchronized.

Hashtable: Similar to HashMap, except that the value of key and value are not allowed to be null; it supports thread synchronization, which means that only one thread can write Hashtable at any one time, thus causing the hashtale to be slower to write.

Linkedhashmap: The insertion Order of the records is saved, and the first record is inserted first when traversing the linkedhashmap with iterator. It is slower than hashmap when traversing. Both the key and value are allowed to be empty, non-synchronous.

Second, map sort

TreeMap

TreeMap is ascending by default, and if we need to change the sorting method, we need to use the comparator: Comparator.

Comparator can be used to sort the collection objects or arrays of the comparator interface, the implementation of the interface of the public compare (T O1,to2) method can be sorted, the method is mainly based on the first parameter O1, less than, equal to or greater than O2 to return a negative integer, 0 or a positive integer respectively. As follows:

Copy CodeThe code is 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) {
Sort Descending
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 ordered based on the key value of treemap, but sometimes we need to sort according to the value of TreeMap. Ordering 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 that the comparer produces. But there is a precondition that all elements must be able to be compared according to the comparator provided. As follows:

Copy CodeThe code is 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");

This converts the Map.entryset () into a list
list<map.entry<string,string>> list = new Arraylist<map.entry<string,string>> (map.entrySet ());
And then sort by the comparator.
Collections.sort (list,new comparator<map.entry<string,string>> () {
Sort Ascending
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 all HashMap values are not sequential, he is based on key hashcode to achieve. How are we going to achieve this sort of unordered hashmap? Referring to the value of TreeMap, we can also implement HashMap sort.

Copy CodeThe code is 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>> () {
Sort Ascending
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

How to sort map in Java (use of map collection)

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.