The Artima Developer Community
Sponsored Link

Java Buzz Forum
How to Sort HashMap in Java based on Keys and Values

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Javin Paul

Posts: 1090
Nickname: javinpaul
Registered: Jan, 2012

Javin Paul is Java Programmer working on Finance domain.
How to Sort HashMap in Java based on Keys and Values Posted: Jan 7, 2015 6:39 AM
Reply to this message Reply

This post originated from an RSS feed registered with Java Buzz by Javin Paul.
Original Post: How to Sort HashMap in Java based on Keys and Values
Feed Title: Java67
Feed URL: http://www.java67.com/feeds/posts/default?alt=rss
Feed Description: Java and technology tutorials, tips, questions for all programmers.
Latest Java Buzz Posts
Latest Java Buzz Posts by Javin Paul
Latest Posts From Java67

Advertisement
HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in a sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn't guarantee any ordering. On other hand, sorting HashMap by values is rather complex because there is no direct method to support that operation. You need to write code for that. In order to sort HashMap by values you can first create a Comparator, which can compare two entries based on values. Then get the Set of entries from Map, convert Set to List and use Collections.sort(List) method to sort your list of entries by values by passing your customized value comparator. This is similar of how you sort an ArrayList in Java. Half of the job is done by now. Now create a new LinkedHashMap and add sorted entries into that. Since LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values.
Read more ยป

Read: How to Sort HashMap in Java based on Keys and Values

Topic: Critical vulnerability in Git clients puts developers at risk Previous Topic   Next Topic Topic: Java : Collection Framework : TreeSet (Alphabets Asc)

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use