How To Split Hashmap Past Times Telephone Substitution In Addition To Value Inwards Coffee - Hashtable, Map Example Tutorial

Sorting HashMap inward Java is non equally piece of cake equally it sounds because unfortunately Java API doesn't supply whatsoever utility method to form HashMap based on keys together with values. Sorting HashMap is non similar sorting ArrayList or sorting Arrays inward Java. If you lot are wondering why nosotros tin non purpose Collections.sort() method than for your information it alone 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, together with LinkedHashMap. TreeMap is an already a sorted Map then nosotros don't demand to form it again. Why nosotros demand to form HashMap inward Java, Why can't nosotros purpose TreeMap inward house of HashMap is the query appears inward almost Java programmer's heed when they asked to form HashMap inward Java. Well, TreeMap is means slower than HashMap because it runs sorting functioning amongst each insertion, update together with removal together with sometimes you lot don't actually demand an all fourth dimension sorted Map, What you lot demand is an mightiness to form whatsoever Map implementation based upon its primal together with value. In the terminal duad of articles, nosotros receive got seen How to loop or traverse Map inward Java together with inward this Java tutorial nosotros volition run into a duad of ways to form HashMap inward Java.


Sorting Map inward Java - By Key

As I said Map or HashMap inward Java tin endure 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 form Map, endure it HashMap or Hashtable yesteryear copying keys into List than sorting List yesteryear using Collections.sort() method, hither you lot tin purpose either Comparator or Comparable based upon whether you lot desire to form on a custom companionship or natural order. 


Once List of keys is sorted, nosotros tin exercise roughly other Map, peculiarly LinkedHashMap to insert keys inward sorted order. LinkedHashMap volition hold the companionship on which keys are inserted, the number is a sorted Map based on keys. This is shown inward the next illustration yesteryear writing a generic parameterized method to form Map based on keys. You tin likewise form Map inward Java yesteryear using TreeMap together with Google Collection API (Guava). The payoff of using Guava is that you lot larn 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 together with You likewise larn a challenge to handgrip goose egg values.

Sorting HashMap inward Java is non equally piece of cake equally it sounds because unfortunately Java API doesn How to form HashMap yesteryear primal together with 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 programme to demonstrate how to form Map inward Java on primal together with values.
 * Map tin endure 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 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 together with 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 primal using TreeMap : " + sortedMapByKeys);
 
     
        //Sorting Map yesteryear keys inward Java using Google Collections (Guava)
        //Main exercise goodness is you lot tin specify whatsoever 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 inward Java using Guava : " + sortingUsingGuava);
     
     

    }
 
    /*
     * Paramterized method to form Map e.g. HashMap or Hashtable inward Java
     * throw NullPointerException if Map contains goose egg 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 companionship 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 inward Java yesteryear value e.g. HashMap or Hashtable
     * throw NullPointerException if Map contains goose egg values
     * It likewise 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 proceed the keys inward the companionship 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 primal using TreeMap : {China=2, England=3, Russia=4, USA=1}
Example to form Map inward Java using Guava : {China=2, England=3, Russia=4, USA=1}


That's all on How to form Map inward Java like HashMap, Hashtable based upon keys together with values. Just think that sorting Map based upon values is to a greater extent than hard than sorting Map based upon keys because values inward Map tin endure either null or duplicates which are non the illustration amongst keys.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt synchronized together with concurrent collection inward Java

Sumber https://javarevisited.blogspot.com/

0 Response to "How To Split Hashmap Past Times Telephone Substitution In Addition To Value Inwards Coffee - Hashtable, Map Example Tutorial"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel