"Sorting HashMap by values in java" Code Answer's
You're definitely familiar with the best coding language Java that developers use to develop their projects and they get all their queries like "Sorting HashMap by values in java" answered properly. Developers are finding an appropriate answer about Sorting HashMap by values in java related to the Java coding language. By visiting this online portal developers get answers concerning Java codes question like Sorting HashMap by values in java. Enter your desired code related query in the search bar and get every piece of information about Java code related question on Sorting HashMap by values in java.
Sorting HashMap by values in java
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class SortHashMapByValue
{
public static void main(String[] args)
{
HashMap<String, Integer> hash = new HashMap<String, Integer>();
hash.put("Toyota", 78);
hash.put("Skoda", 69);
hash.put("Honda", 93);
hash.put("Audi", 59);
hash.put("Chevrolet", 39);
hash.put("Hyundai", 56);
Map<String, Integer> map = sortByValue(hash);
System.out.println("Sorting hashmap by values in java: ");
// printing sorted HashMap
for(Map.Entry<String, Integer> me : map.entrySet())
{
System.out.println("Key = " + me.getKey() + ", Value = " + me.getValue());
}
}
public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm)
{
// creating list from elements of HashMap
List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());
// sorting list
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>()
{
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
return (o1.getValue()).compareTo(o2.getValue());
}
});
HashMap<String, Integer> ha = new LinkedHashMap<String, Integer>();
for(Map.Entry<String, Integer> me : list)
{
ha.put(me.getKey(), me.getValue());
}
return ha;
}
}
Source: www.flowerbrackets.com
All those coders who are working on the Java based application and are stuck on Sorting HashMap by values in java can get a collection of related answers to their query. Programmers need to enter their query on Sorting HashMap by values in java related to Java code and they'll get their ambiguities clear immediately. On our webpage, there are tutorials about Sorting HashMap by values in java for the programmers working on Java code while coding their module. Coders are also allowed to rectify already present answers of Sorting HashMap by values in java while working on the Java language code. Developers can add up suggestions if they deem fit any other answer relating to "Sorting HashMap by values in java". Visit this developer's friendly online web community, CodeProZone, and get your queries like Sorting HashMap by values in java resolved professionally and stay updated to the latest Java updates.