Map sort (sort by key, sort by value)

Source: Internet
Author: User

There are two main types, key sorting, sorting by value. Also, sorting by key is used primarily for treemap, while sorting by value is appropriate for the subclass of map.

first, the key sort

Sort by key is mainly used for treemap, can be implemented according to the size of the key value, when the object is inserted directly into the appropriate position, to maintain the order of the map.

Look at the constructor of TreeMap: TreeMap(Comparator<? super K> comparator): constructs a new, empty tree map that is sorted by the given comparer.

The comparator here is the comparator for key. So the two parameters that are used for comparison when defining a comparer are objects of the data type of key.

The instance code is as follows:

 Public classMapsorttest { Public Static voidMain (string[] args) { Map <String,String> stu=new treemap<> (New Mycomparator ());//Pass in a key comparator object to construct the TreeMapStu.put ("Apple", "55"); Stu.put ("Boy", "32"); Stu.put ("Cat", "22"); Stu.put ("Dog", "12"); Stu.put ("Egg", "11"); //Map Traversal: Extract the key out of the set, then use the iterator to traverse the keyset, and use Map.get (key) to get the value corresponding to key. Set<String> keyset=Stu. KeySet  (); Iterator it=Keyset.iterator ();  while(It.hasnext ()) {String Next=(String) it.next (); System.out.println (Next+","+Stu.get (next)); }}}//the comparator that defines the key, the comparison algorithm according to the first parameter O1, less than, equal to or greater than O2 respectively return a negative integer, 0 or a positive integer, to determine the position of the two deposit: return negative number is O1 before, positive number is O2 in front. class Mycomparator Implements Comparator<String>{ Public int Compare(String O1, String O2) {returnO1.compareto (O2); }}
second, sort by value

Sorting by value only uses treemap, sorting by value because of the uniformity of the type used by its methods, so it can be used for all subclasses of map .

The main points of knowledge used are;

1:map. EntrySet() takes each key-value pair out of the map and encapsulates it into a entry object and puts it into a set.

2: Generic map.entry<type1,type2> because Key-value is a Entry object, this indicates the data type of the two members in the Entry object.

3:collections.sort (list<t> List, comparator<? super t> C) The sorting method of the collection class, sorted by a custom comparer. The list here holds objects that are entry objects. Defines the comparer to compare the Value property in the Entry object .

The instance code is as follows:

 Public classMapsorttest { Public Static voidMain (string[] args) { Map <String,String> stu=new treemap<> ();//Storage with TreeMap//map<string,string> stu=new hashmap<> ();//Storage with HashMapStu.put ("Apple", "55"); Stu.put ("Boy", "32"); Stu.put ("Cat", "22"); Stu.put ("Dog", "12"); Stu.put ("Egg", "11"); //1: Convert map to EntrySet and convert to list to save entry object.       list<map.entry<string,string>> entrys=new arraylist<>(Stu.entryset ());    //2: Call Collections.sort (List,comparator) method to sort Entry-list      Collections.sort (Entrys, Newmycomparator ());    //3: Traverse the ordered entry-list, can get the result of output sequentially       for(map.entry<string,string>Entry:entrys) {System.out.println (Entry.getkey ()+","+Entry.getvalue ()); }}}//the comparer for the custom entry object. Each entry object can be used by Getkey (), GetValue () to obtain a key or value for comparison. In other words: we can also sort by key by entry object implementation.     class Mycomparator ImplementsComparator<map.entry>{ Public intCompare (Map.entry O1, Map.entry O2) {return(String) O1.getvalue ()). CompareTo (String) o2.getvalue ()); }}

Map sort (sort by key, sort by value)

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.