Sorting and traversing hashmap in Java

Source: Internet
Author: User

Hashmap sorting

1. sort by key

For map sorting in Java, there is a Sort map, such as treemap. For this map, you can only sort by key first, and then sort by put and remove, performance may be compromised.

In this solution, hashmap is used for creation and addition. If you want to sort by key, you can pass this hashmap as a parameter to new treemap (hashmap). Then you can sort by key:

Treemap =NewTreemap (hashmap );

Treemap = new treemap (hashmap );

2. sort by value

Use hashmap, add comparator, and sort

Map <string, integer> keyfreqs =NewHashmap <string, integer> ();

Arraylist <entry <string, integer> L =NewArraylist <entry <string, integer> (keyfreqs. entryset ());

Collections. Sort (L,NewComparator <map. Entry <string, integer> (){


Public IntCompare (Map. Entry <string, integer> O1, map. Entry <string, integer> O2 ){


Return(O2.getvalue ()-o1.getvalue ());}});

For(Entry <string, integer> E: l ){

System. Out. println (E. getkey () + ":" + E. getvalue ());

}

 

Hashmap Traversal

In Java, hashmap is mainly used in two traversal methods. The Code is as follows:

First:

Hashmap = new hashmap ();

Iterator = hashmap. keyset (). iterator ();

While (iterator. hasnext ()){

Object value = hashmap. Get (iterator. Next ());

}

 

Second:

Hashmap = new hashmap ();

Iterator = hashmap. entryset (). iterator ();

While (iterator. hasnext ()){

Entry entry = (entry) iterator. Next ();

Object value = entry. getvalue ();

Object key = entry. getkey ();

}

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.