How To Assort Hashmap Past Times Cardinal As Well As Value Inwards Coffee - Hashtable, Map Illustration Tutorial

Sorting HashMap inward Java is non every bit piece of cake every bit it sounds because unfortunately Java API doesn't render whatever utility method to variety HashMap based on keys as well as values. Sorting HashMap is non similar sorting ArrayList or sorting Arrays inward Java. If you lot are wondering why nosotros tin terminate non role Collections.sort() method than for your information it solely accepts List<E>, which leaves us to write our ain utility methods to sort Map inward Java. This is truthful for all types of Map similar Hashtable, HashMap, as well as LinkedHashMap. TreeMap is an already a sorted Map then nosotros don't demand to variety it again. Why nosotros demand to variety HashMap inward Java, Why can't nosotros role TreeMap inward house of HashMap is the interrogation appears inward near Java programmer's take away heed when they asked to variety HashMap inward Java. Well, TreeMap is agency slower than HashMap because it runs sorting functioning alongside each insertion, update as well as removal as well as sometimes you lot don't actually demand an all fourth dimension sorted Map, What you lot demand is an mightiness to variety whatever Map implementation based upon its telephone commutation as well as value. In the terminal yoke of articles, nosotros receive got seen How to loop or traverse Map inward Java as well as inward this Java tutorial nosotros volition encounter a yoke of ways to variety HashMap inward Java.


Sorting Map inward Java - By Key

As I said Map or HashMap inward Java tin terminate 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 merely doesn't allow duplicates keys. You tin terminate variety Map, hold upwards it HashMap or Hashtable yesteryear copying keys into List than sorting List yesteryear using Collections.sort() method, hither you lot tin terminate role either Comparator or Comparable based upon whether you lot desire to variety on a custom social club or natural order. 


Once List of keys is sorted, nosotros tin terminate exercise approximately other Map, specially LinkedHashMap to insert keys inward sorted order. LinkedHashMap volition keep the social club on which keys are inserted, the resultant is a sorted Map based on keys. This is shown inward the next illustration yesteryear writing a generic parameterized method to variety Map based on keys. You tin terminate every bit good variety Map inward Java yesteryear using TreeMap as well as Google Collection API (Guava). The wages of using Guava is that you lot larn approximately flexibility on specifying ordering.


Sorting Map inward Java - By Value

Sorting Map inward 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 as well as You every bit good larn a challenge to handgrip nada values.

Sorting HashMap inward Java is non every bit piece of cake every bit it sounds because unfortunately Java API doesn How to variety HashMap yesteryear telephone commutation as well as value inward Java - Hashtable, Map Example Tutorialpackage 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 variety Map inward Java on telephone commutation as well as values.
 * Map tin terminate hold upwards variety 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 inward Java : " + olympic2012);
     
        //sorting Map e.g. HashMap, Hashtable yesteryear keys inward Java
        Map<String, Integer> sorted = sortByKeys(olympic2012);
        System.out.println("Sorted Map inward Java yesteryear key: " + sorted);
     
     
        //sorting Map similar Hashtable as well as HashMap yesteryear values inward Java
        sorted = sortByValues(olympic2012);
        System.out.println("Sorted Map inward Java yesteryear values: " + sorted);
     
     
        //Sorting Map inward Java yesteryear keys using TreeMap
        Map<String, Integer> sortedMapByKeys = new TreeMap<String,Integer>();
        sortedMapByKeys.putAll(olympic2012);
        System.out.println("Sorted Map inward Java yesteryear telephone commutation using TreeMap : " + sortedMapByKeys);
 
     
        //Sorting Map yesteryear keys inward Java using Google Collections (Guava)
        //Main exercise goodness is you lot tin terminate 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 variety Map inward Java using Guava : " + sortingUsingGuava);
     
     

    }
 
    /*
     * Paramterized method to variety Map e.g. HashMap or Hashtable inward Java
     * throw NullPointerException if Map contains nada 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 dice along the keys inward the social club 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 variety Map inward Java yesteryear value e.g. HashMap or Hashtable
     * throw NullPointerException if Map contains nada values
     * It every bit good variety 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 dice along the keys inward the social club 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 inward Java : {USA=1, England=3, Russia=4, China=2}
Sorted Map inward Java yesteryear key: {China=2, England=3, Russia=4, USA=1}
Sorted Map inward Java yesteryear values: {USA=1, China=2, England=3, Russia=4}
Sorted Map inward Java yesteryear telephone commutation using TreeMap : {China=2, England=3, Russia=4, USA=1}
Example to variety Map inward Java using Guava : {China=2, England=3, Russia=4, USA=1}


That's all on How to variety Map inward Java like HashMap, Hashtable based upon keys as well as values. Just scream upwards that sorting Map based upon values is to a greater extent than hard than sorting Map based upon keys because values inward Map tin terminate 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 as well as concurrent collection inward Java

Belum ada Komentar untuk "How To Assort Hashmap Past Times Cardinal As Well As Value Inwards Coffee - Hashtable, Map Illustration Tutorial"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel