How To Form Out Hashmap Past Times Fundamental Too Value Inwards Coffee - Hashtable, Map Event Tutorial
Sorting HashMap inwards Java is non equally piece of cake equally it sounds because unfortunately Java API doesn't render whatever utility method to form HashMap based on keys in addition to values. Sorting HashMap is non similar sorting ArrayList or sorting Arrays inwards Java. If yous are wondering why nosotros tin mail away non role Collections.sort() method than for your information it alone accepts List<E>, which leaves us to write our ain utility methods to sort Map inwards Java. This is truthful for all types of Map similar Hashtable, HashMap, in addition to LinkedHashMap. TreeMap is an already a sorted Map then nosotros don't demand to form it again. Why nosotros demand to form HashMap inwards Java, Why can't nosotros role TreeMap inwards house of HashMap is the inquiry appears inwards around Java programmer's heed when they asked to form HashMap inwards Java. Well, TreeMap is agency slower than HashMap because it runs sorting functioning alongside each insertion, update in addition to removal in addition to sometimes yous don't actually demand an all fourth dimension sorted Map, What yous demand is an mightiness to form whatever Map implementation based upon its fundamental in addition to value. In the terminal span of articles, nosotros receive got seen How to loop or traverse Map inwards Java in addition to inwards this Java tutorial nosotros volition run into a span of ways to form HashMap inwards Java.
Sorting Map inwards Java - By Key
As I said Map or HashMap inwards Java tin mail away hold upwards sorted either on keys or values. Sorting Map on keys is rather piece of cake than sorting on values because Map allows duplicate values exactly doesn't allow duplicates keys. You tin mail away form Map, hold upwards it HashMap or Hashtable past times copying keys into List than sorting List past times using Collections.sort() method, hither yous tin mail away role either Comparator or Comparable based upon whether yous desire to form on a custom lodge or natural order.
Once List of keys is sorted, nosotros tin mail away exercise around other Map, especially LinkedHashMap to insert keys inwards sorted order. LinkedHashMap volition hold the lodge on which keys are inserted, the trial is a sorted Map based on keys. This is shown inwards the next illustration past times writing a generic parameterized method to form Map based on keys. You tin mail away equally good form Map inwards Java past times using TreeMap in addition to Google Collection API (Guava). The payoff of using Guava is that yous teach around flexibility on specifying ordering.
Once List of keys is sorted, nosotros tin mail away exercise around other Map, especially LinkedHashMap to insert keys inwards sorted order. LinkedHashMap volition hold the lodge on which keys are inserted, the trial is a sorted Map based on keys. This is shown inwards the next illustration past times writing a generic parameterized method to form Map based on keys. You tin mail away equally good form Map inwards Java past times using TreeMap in addition to Google Collection API (Guava). The payoff of using Guava is that yous teach around flexibility on specifying ordering.
Sorting Map inwards Java - By Value
Sorting Map inwards Java e.g. HashMap or Hashtable based upon values is to a greater extent than hard than sorting Map based on keys because Map allows duplicate values in addition to You equally good teach a challenge to handgrip zilch values.
package test;import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
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;
import java.util.Map.Entry;
import java.util.TreeMap;
/**
*
* Java plan to demonstrate how to form Map inwards Java on fundamental in addition to values.
* Map tin mail away hold upwards form on keys or values.
*
* @author Javin Paul
*/
public class MapSortingExample {
public static void main(String args[]) {
//creating Hashtable for sorting
Map<String, Integer> olympic2012 = new HashMap<String, Integer>();
olympic2012.put("England", 3);
olympic2012.put("USA", 1);
olympic2012.put("China", 2);
olympic2012.put("Russia", 4);
//olympic2012.put("Australia", 4); //adding duplicate value
//printing hashtable without sorting
System.out.println("Unsorted Map inwards Java : " + olympic2012);
//sorting Map e.g. HashMap, Hashtable past times keys inwards Java
Map<String, Integer> sorted = sortByKeys(olympic2012);
System.out.println("Sorted Map inwards Java past times key: " + sorted);
//sorting Map similar Hashtable in addition to HashMap past times values inwards Java
sorted = sortByValues(olympic2012);
System.out.println("Sorted Map inwards Java past times values: " + sorted);
//Sorting Map inwards Java past times keys using TreeMap
Map<String, Integer> sortedMapByKeys = new TreeMap<String,Integer>();
sortedMapByKeys.putAll(olympic2012);
System.out.println("Sorted Map inwards Java past times fundamental using TreeMap : " + sortedMapByKeys);
//Sorting Map past times keys inwards Java using Google Collections (Guava)
//Main exercise goodness is yous tin mail away specify whatever ordering similar natural or toString or arbitrary
Map<String, Integer> sortingUsingGuava = Maps.newTreeMap(Ordering.natural());
sortingUsingGuava.putAll(olympic2012);
System.out.println("Example to form Map inwards Java using Guava : " + sortingUsingGuava);
}
/*
* Paramterized method to form Map e.g. HashMap or Hashtable inwards Java
* throw NullPointerException if Map contains zilch key
*/
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByKeys(Map<K,V> map){
List<K> keys = new LinkedList<K>(map.keySet());
Collections.sort(keys);
//LinkedHashMap volition popular off on the keys inwards the lodge they are inserted
//which is currently sorted on natural ordering
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(K key: keys){
sortedMap.put(key, map.get(key));
}
return sortedMap;
}
/*
* Java method to form Map inwards Java past times value e.g. HashMap or Hashtable
* throw NullPointerException if Map contains zilch values
* It equally good form values fifty-fifty if they are duplicates
*/
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
//LinkedHashMap volition popular off on the keys inwards the lodge they are inserted
//which is currently sorted on natural ordering
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entry: entries){
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
Output
Unsorted Map inwards Java : {USA=1, England=3, Russia=4, China=2}
Sorted Map inwards Java past times key: {China=2, England=3, Russia=4, USA=1}
Sorted Map inwards Java past times values: {USA=1, China=2, England=3, Russia=4}
Sorted Map inwards Java past times fundamental using TreeMap : {China=2, England=3, Russia=4, USA=1}
Example to form Map inwards Java using Guava : {China=2, England=3, Russia=4, USA=1}
That's all on How to form Map inwards Java like HashMap, Hashtable based upon keys in addition to values. Just hollo back that sorting Map based upon values is to a greater extent than hard than sorting Map based upon keys because values inwards Map tin mail away hold upwards either null or duplicates which are non the instance alongside keys.
Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt synchronized in addition to concurrent collection inwards Java
Komentar
Posting Komentar