How the Map collection order in Java is as __java as adding order

Source: Internet
Author: User

The most common use of map is HashMap, but hashmap elements are not in the order to add, then in addition to the use of HASHMAP, what map interface implementation classes can be used.

There are 2 of them, TreeMap and Linkedhashmap, but to meet our requirements: Save elements in the order of addition, only linkedhashmap.

Look at the code running below.

Package com.lxk.collectionTest;

Import Com.google.common.collect.Maps;

Import Java.util.Map; /** * Test Map for order difference * <p> * Created by LXK on 2017/5/24 */public class Orderedmaptest {public static void M
        Ain (string[] args) {map<string, integer> hashMap = Maps.newhashmap ();
        map<string, integer> treeMap = Maps.newtreemap ();
        map<string, integer> linkedhashmap = Maps.newlinkedhashmap ();
        System.out.println ("--------------test HashMap");
        TestMap (HASHMAP);
        System.out.println ("--------------test TreeMap");
        TestMap (TREEMAP);
        System.out.println ("--------------test Linkedhashmap");
    TestMap (LINKEDHASHMAP);
        private static void TestMap (Map<string, integer> Map) {map.put ("ASD", 1);
        Map.put ("2das", 2);
        Map.put ("3das", 3);
        Map.put ("4das", 4); For (map.entry<string, integer> entry:map.entrySet ()) {System.out.println (Entry).Getkey () + ":" + entry.getvalue ());
 }
    }

}

Then there is the graph of the running results.



As you can see, if you just say orderly, then the hashmap is disorderly, but, to add the order, it is only linkedhashmap.



I finished writing the article, to give myself a little praise, not too much,
But I'm going to order it.
I'll start with a toast, you're free. Everyone is free. Don't be polite ...


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.