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

Advertisement

Masukkan script iklan 970x90px

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

Sabtu, 30 Mei 2020

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 kind HashMap based on keys in addition to values. Sorting HashMap is non similar sorting ArrayList or sorting Arrays inward Java. If yous are wondering why nosotros tin 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, in addition to LinkedHashMap. TreeMap is an already a sorted Map in addition to then nosotros don't demand to kind it again. Why nosotros demand to kind HashMap inward Java, Why can't nosotros role TreeMap inward house of HashMap is the enquiry appears inward almost Java programmer's hear when they asked to kind HashMap inward Java. Well, TreeMap is means 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 kind whatever Map implementation based upon its fundamental in addition to value. In the final dyad of articles, nosotros receive got seen How to loop or traverse Map inward Java in addition to inward this Java tutorial nosotros volition run across a dyad of ways to kind HashMap inward Java.


Sorting Map inward Java - By Key

As I said Map or HashMap inward Java tin last sorted either on keys or values. Sorting Map on keys is rather piece of cake than sorting on values because Map allows duplicate values precisely doesn't allow duplicates keys. You tin kind Map, last it HashMap or Hashtable past times copying keys into List than sorting List past times using Collections.sort() method, hither yous tin role either Comparator or Comparable based upon whether yous desire to kind on a custom firm or natural order. 


Once List of keys is sorted, nosotros tin practise roughly other Map, peculiarly LinkedHashMap to insert keys inward sorted order. LinkedHashMap volition keep the firm on which keys are inserted, the lawsuit is a sorted Map based on keys. This is shown inward the next instance past times writing a generic parameterized method to kind Map based on keys. You tin besides kind Map inward Java past times using TreeMap in addition to Google Collection API (Guava). The payoff of using Guava is that yous teach roughly 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 in addition to You besides teach a challenge to handgrip zip values.

Sorting HashMap inward Java is non every bit piece of cake every bit it sounds because unfortunately Java API doesn How to kind HashMap past times fundamental in addition to 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 kind Map inward Java on fundamental in addition to values.
 * Map tin last kind 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 past times keys inward Java
        Map<String, Integer> sorted = sortByKeys(olympic2012);
        System.out.println("Sorted Map inward Java past times key: " + sorted);
     
     
        //sorting Map similar Hashtable in addition to HashMap past times values inward Java
        sorted = sortByValues(olympic2012);
        System.out.println("Sorted Map inward Java past times values: " + sorted);
     
     
        //Sorting Map inward Java past times keys using TreeMap
        Map<String, Integer> sortedMapByKeys = new TreeMap<String,Integer>();
        sortedMapByKeys.putAll(olympic2012);
        System.out.println("Sorted Map inward Java past times fundamental using TreeMap : " + sortedMapByKeys);
 
     
        //Sorting Map past times keys inward Java using Google Collections (Guava)
        //Main practise goodness is yous tin 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 kind Map inward Java using Guava : " + sortingUsingGuava);
     
     

    }
 
    /*
     * Paramterized method to kind Map e.g. HashMap or Hashtable inward Java
     * throw NullPointerException if Map contains zip 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 proceed the keys inward the firm 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 kind Map inward Java past times value e.g. HashMap or Hashtable
     * throw NullPointerException if Map contains zip values
     * It besides kind 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 proceed the keys inward the firm 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 past times key: {China=2, England=3, Russia=4, USA=1}
Sorted Map inward Java past times values: {USA=1, China=2, England=3, Russia=4}
Sorted Map inward Java past times fundamental using TreeMap : {China=2, England=3, Russia=4, USA=1}
Example to kind Map inward Java using Guava : {China=2, England=3, Russia=4, USA=1}


That's all on How to kind Map inward Java like HashMap, Hashtable based upon keys in addition to values. Just recollect that sorting Map based upon values is to a greater extent than hard than sorting Map based upon keys because values inward Map tin last 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 inward Java