JAVA Map Ascending | descending | random | reordering

Source: Internet
Author: User
Tags shuffle
I. Map INTRODUCTION


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):

1, HashMap: Our most commonly used map, it is based on the key hashcode value to store data, according to the key can directly obtain its value, while it has a 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.

2, TreeMap: can keep it records according to key sort, by default is sorted in ascending order, can also specify the sort of comparator, when using iterator traversal TreeMap, the record is ordered. TreeMap does not allow the value of key to be null. is not synchronized.

3, Hashtable: Similar to the HashMap, the difference is that the value of key and value are not allowed to null; it supports thread synchronization, in which only one thread can write Hashtable at any one time, and therefore hashtale is slower when writing.

4, Linkedhashmap: Save the record of the insertion order, in the iterator traversal Linkedhashmap, 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.


Briefly summed up as:

Map: Unordered
Treemap: Default is ascending (with key as standard)
Linkedhashmap: The default is the order in which data is inserted



second, comparator interface


(A), Methods

int compare (T o1,t O2)

(B), description


Compares the two parameters used to sort. Returns a negative integer, 0, or positive integer, respectively, based on the first argument less than, equal to, or greater than the second argument.
In the previous description, the symbol SGN (expression) represents a Signum mathematical function that returns 1, 0, or 1, depending on whether the expression value is negative, 0, or positive.


In simple terms, the comparer interface that comparator can sort a collection object or array, implementing the public compare (T O1,to2) method of the interface can be sorted, which is mainly based on the first parameter O1, less than, equal to, or greater than O2 to return negative integers respectively , 0, or positive integer.


(C), Parameters:
O1-The first object to compare.
O2-The second object to compare.


(D), return:
Returns a negative integer, 0, or positive integer, respectively, based on the first argument less than, equal to, or greater than the second argument.


third, the example


1, key sorting


Treemap<k,v> can satisfy this kind of requirement, TREEMAP (comparator<, Super k> Comparator) to its construction method, we can sort the key by passing in our custom comparer.

    /**
     * Sort by key *
     *
    @Test public
    void TestSort1 () {
        map<string, string> resultmap = new TreeMap <> (New comparator<string> () {
            @Override public
            int Compare (string str1, String str2) {
                return Str1.compareto (STR2);
            }
        );
        Resultmap.put ("1", "KFC");
        Resultmap.put ("2", "WNBA");
        Resultmap.put ("3", "NBA");
        Resultmap.put ("4", "CBA");
        For (map.entry<string, string> entry:resultMap.entrySet ()) {
            System.out.println (Entry.getkey () + "" + Entry . GetValue ());
        }
    



2, sorted by value


The map itself is very meaningful to sort by value, and many situations encounter similar requirements, which can be considered a rule or weight defined.

Principle: Put all elements in a sorted map in a list, and then use a static method of collections sort (list<t> list, comparator< super t> C)
To arrange a sequence table, and also to define a comparison rule with a comparer. The elements in the sorted list are then loaded into the map, and the Linkedhashmap data type is used to ensure that the elements in the map are in the same order as the elements in the ordered list.


    /** * Sorted by value * * @Test public void TestSort2 () {map<string, string> resultmap = new
        Treemap<string, string> ();
        Resultmap.put ("KFC", "1");
        Resultmap.put ("WNBA", "2");
        Resultmap.put ("NBA", "6");
        Resultmap.put ("CBA", "4");
        Resultmap.put ("EBA", "5");
        Resultmap.put ("Ebe", "0");
        map<string, string> sortedmap = new linkedhashmap<string, string> ();
                list<map.entry<string, string>> entrylist = new arraylist<map.entry<string, String>> (

        Resultmap.entryset ());  Collections.sort (entrylist, New comparator<entry<string, string>> () {@Override public int compare (entry<string, string> O1, entry<string, string> O2) {return O1.getvalue (). compar
            ETo (O2.getvalue ());

        }
        });
  Iterator<map.entry<string, string>> iter = Entrylist.iterator ();      map.entry<string, string> tmpentry = null;
            while (Iter.hasnext ()) {tmpentry = Iter.next ();
        Sortedmap.put (Tmpentry.getkey (), Tmpentry.getvalue ()); For (map.entry<string, string> entry:sortedMap.entrySet ()) {System.out.println (Entry.getke
        Y () + "" + Entry.getvalue ()); }
    }

3. Random Ordering


   /** * Three sort of * 1. Ascending order * 2. Descending sort * 3. Random sort/@Test public void TestSort3 () {//default
        
        TreeMap in ascending order Treemap<integer, integer> map1 = new Treemap<integer, integer> (); Descending sort Treemap<integer, integer> map2 = new Treemap<integer, integer> (New comparator<integer> () {/* * int Compare (object O1, Object O2) returns an integer of the base type, * Returns a negative number indicating: O1 less than O2, *
            Returns 0: O1 and O2 are equal, * returns a positive number indicating: O1 is greater than O2.
            * * public int compare (integer o1, integer o2) {return o2-o1;

        }
        }); Random sort Treemap<integer, integer> map3 = new Treemap<integer, integer> (New comparator<integer> () {/* * int Compare (object O1, Object O2) returns an integer of the base type, * Returns a negative number indicating: O1 less than O2, *
            Returns 0: O1 and O2 are equal, * returns a positive number indicating: O1 is greater than O2. */public int Compare(integer A, integer b)
                {int randomone = (int) (Math.random () * 10);
                int randomtwo = (int) (Math.random () * 10);
            return randomone-randomtwo;

        }
        });
        Map2.put (1, 2);
        Map2.put (2, 4);
        Map2.put (2, 4);
        Map2.put (7, 1);
        Map2.put (5, 2);

        System.out.println ("Map2 descending order =" + MAP2);
        Map1.put (1, 2);
        Map1.put (2, 4);
        Map1.put (7, 1);
        Map1.put (5, 2);
        Map1.put (5, 2);

        System.out.println ("map1 ascending sort =" + Map1);
        Map3.put (1, 2);
        Map3.put (2, 4);
        Map3.put (7, 1);
        Map3.put (5, 2);
        Map3.put (9, 2);
        Map3.put (11, 2);
        Map3.put (11, 2);
    System.out.println ("map3 random sort =" + map3);
 }

4.Map convert to list using Collections.shuffle () random sort

    /** * Map List Random sort * @throws IOException/@Test public void TestSort4 () throws IOException {
        map<string, object> unsortmap = new hashmap<> ();
        Unsortmap.put ("Z", 10);
        Unsortmap.put ("B", 5);
        Unsortmap.put ("A", 6);
        Unsortmap.put ("C", 20);
        Unsortmap.put ("D", 1);
        Unsortmap.put ("E", 7);
        Unsortmap.put ("Y", 8);
        Unsortmap.put ("n", 99);
        Unsortmap.put ("G", 50);
        Unsortmap.put ("M", 2);
        Unsortmap.put ("F", 9);
        list<string> list = new LinkedList (Unsortmap.keyset ());
        Random sort collections.shuffle (list);
        map<string,object> result = new hashmap<string,object> ();
            for (int i = 0; i < list.size (); i++) {String jsonstring = List.get (i);
        Result.put (jsonstring, Unsortmap.get (jsonstring)); For (map.entry<string, object> entry:result.entrySet ()) {System.out. println (Entry.getkey () + "" + Entry.getvalue ()); }
    }


Related Article

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.