Linkedhashmap sorting map According to put order

Source: Internet
Author: User

In the recent project, the report needs to be aggregated because all the items are dynamic and can only be added dynamically.

The idea is to use map, initialize all maps, and then aggregate and overwrite them in the map.

With HashMap, the order of all dynamic items after initialization is messed up.

map<string, double> totalmap = new hashmap<string, double> ();
For (map<string, object> map:itemlist) {
Itemsql + = "SUM (" +map.get ("item_no") + ") as" +map.get ("item_no") + ",";
Totalmap.put (Map.get ("Item_no"). ToString (), 0d);
}

TreeMap also can not meet my needs, treemap belong to the natural sort. Dynamic items are definitely manually adjusted, and I just need to sort by the put order.

Google, found that the HashMap subclass Linkedhashmap can implement the iteration order (both the insertion Order) code as follows:

map<string, double> totalmap = new linkedhashmap<string, double> (); For statistical dynamic items
For (map<string, object> map:itemlist) {
Itemsql + = "SUM (" +map.get ("item_no") + ") as" +map.get ("item_no") + ",";
Totalmap.put (Map.get ("Item_no"). ToString (), 0d);
}

All right, this is done.

Linkedhashmap sorting map According to put order

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.