Wednesday, December 11, 2019

How To Course Of Didactics Hashmap Inward Coffee Based On Keys Together With Values

HashMap is non meant to proceed entries inwards sorted order, but if you lot guide hold to form HashMap based upon keys or values, you lot tin practice that inwards Java. Sorting HashMap on keys is quite easy, all you lot demand to practice is to practice a TreeMap past times copying entries from HashMap. TreeMap is an implementation of SortedMap as well as keeps keys inwards their natural club or a custom club specified past times Comparator provided piece creating TreeMap. This way you lot tin procedure entries of HashMap inwards a sorted club but you lot cannot top a HashMap containing mappings inwards a specific order, this is simply non possible because HashMap doesn't guarantee whatsoever ordering. On other hand, sorting HashMap past times values is rather complex because at that spot is no straight method to back upward that operation. You demand to write code for that. In club to form HashMap past times values you lot tin starting fourth dimension practice a Comparator, which tin compare 2 entries based on values. Then acquire the Set of entries from Map, convert Set to List as well as usage Collections.sort(List) method to form your listing of entries past times values past times passing your customized value comparator. This is like of how you lot form an ArrayList inwards Java. Half of the undertaking is done past times now. Now practice a novel LinkedHashMap as well as add together sorted entries into that. Since LinkedHashMap guarantees insertion club of mappings, you lot volition survive guide hold a Map where contents are sorted past times values.



Steps to form HashMap past times values

One deviation betwixt sorting HashMap past times keys as well as values is that it tin incorporate duplicate values past times non duplicate keys. You cannot usage TreeMap hither because it exclusively form entries past times keys. In this illustration you lot demand to :
  1. Get all entries past times calling entrySet() method of Map
  2. Create a custom Comparator to form entries based upon values
  3. Convert entry laid upward to list
  4. Sort entry listing past times using Collections.sort() method past times passing your value comparator
  5. Create a LinkedHashMap past times adding entries inwards sorted order.




Steps to form HashMap past times keys

There are 2 ways to sort HashMap past times keys, starting fourth dimension past times using TreeMap as well as minute past times using LinkedHashMap. If you lot desire to form using TreeMap as well as hence it's simple, simply practice a TreeMap past times copying content of HashMap. On the other hand, if you lot desire to practice a LinkedHashMap as well as hence you lot starting fourth dimension demand to acquire key set, convert that Set to List, form that List as well as and hence add together them into LHM inwards same order. Remember HashMap tin incorporate i null key but duplicate keys are non allowed.



HashMap Sorting past times Keys as well as Values inwards Java Example

overrides comapre() method as well as accepts 2 entries. Later it retrieves values from those entries as well as compare them as well as render result. Since at that spot is no method inwards Java Collection API to form Map, nosotros demand to usage Collections.sort() method which accepts a List. This involves creating a temporary ArrayList alongside entries for sorting usage as well as and hence in i lawsuit again copying entries from sorted ArrayList to a novel LinkedHashMap to proceed them inwards sorted order. Finally nosotros practice a HashMap from that LinkedHashMap, which is what nosotros needed.

import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.TreeMap;  /**  * How to form HashMap inwards Java past times keys as well as values.   * HashMap doesn't guarantee whatsoever order, hence you lot cannot rely on it, fifty-fifty if  * it seem that it storing entries inwards a detail order, because  * it may non live available inwards hereafter version e.g. before HashMap stores  * integer keys on the club they are inserted but from Java 8 it has changed.  *   * @author WINDOWS 8  */  public class HashMapSorting{      public static void main(String args[]) throws ParseException {                  // let's practice a map alongside Java releases as well as their code names         HashMap<String, String> codenames = new HashMap<String, String>();                  codenames.put("JDK 1.1.4", "Sparkler");         codenames.put("J2SE 1.2", "Playground");         codenames.put("J2SE 1.3", "Kestrel");         codenames.put("J2SE 1.4", "Merlin");         codenames.put("J2SE 5.0", "Tiger");         codenames.put("Java SE 6", "Mustang");         codenames.put("Java SE 7", "Dolphin");                  System.out.println("HashMap before sorting, random club ");         Set<Entry<String, String>> entries = codenames.entrySet();                 for(Entry<String, String> entry : entries){             System.out.println(entry.getKey() + " ==> " + entry.getValue());         }                  // Now let's form HashMap past times keys starting fourth dimension          // all you lot demand to practice is practice a TreeMap alongside mappings of HashMap         // TreeMap keeps all entries inwards sorted order         TreeMap<String, String> sorted = new TreeMap<>(codenames);         Set<Entry<String, String>> mappings = sorted.entrySet();                  System.out.println("HashMap afterwards sorting past times keys inwards ascending club ");         for(Entry<String, String> mapping : mappings){             System.out.println(mapping.getKey() + " ==> " + mapping.getValue());         }                           // Now let's form the HashMap past times values         // at that spot is no straight way to form HashMap past times values but you         // tin practice this past times writing your ain comparator, which takes         // Map.Entry object as well as suit them inwards club increasing          // or decreasing past times values.                  Comparator<Entry<String, String>> valueComparator = new Comparator<Entry<String,String>>() {                          @Override             public int compare(Entry<String, String> e1, Entry<String, String> e2) {                 String v1 = e1.getValue();                 String v2 = e2.getValue();                 return v1.compareTo(v2);             }         };                  // Sort method needs a List, hence let's starting fourth dimension convert Set to List inwards Java         List<Entry<String, String>> listOfEntries = new ArrayList<Entry<String, String>>(entries);                  // sorting HashMap past times values using comparator         Collections.sort(listOfEntries, valueComparator);                  LinkedHashMap<String, String> sortedByValue = new LinkedHashMap<String, String>(listOfEntries.size());                  // copying entries from List to Map         for(Entry<String, String> entry : listOfEntries){             sortedByValue.put(entry.getKey(), entry.getValue());         }                  System.out.println("HashMap afterwards sorting entries past times values ");         Set<Entry<String, String>> entrySetSortedByValue = sortedByValue.entrySet();                  for(Entry<String, String> mapping : entrySetSortedByValue){             System.out.println(mapping.getKey() + " ==> " + mapping.getValue());         }     }       }  Output: HashMap before sorting, random club  Java SE 7 ==> Dolphin J2SE 1.2 ==> Playground Java SE 6 ==> Mustang J2SE 5.0 ==> Tiger J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin JDK 1.1.4 ==> Sparkler HashMap afterwards sorting past times keys inwards ascending club  J2SE 1.2 ==> Playground J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin J2SE 5.0 ==> Tiger JDK 1.1.4 ==> Sparkler Java SE 6 ==> Mustang Java SE 7 ==> Dolphin HashMap afterwards sorting entries past times values  Java SE 7 ==> Dolphin J2SE 1.3 ==> Kestrel J2SE 1.4 ==> Merlin Java SE 6 ==> Mustang J2SE 1.2 ==> Playground JDK 1.1.4 ==> Sparkler J2SE 5.0 ==> Tiger

That's all nigh how to form HashMap past times keys as well as values inwards Java. Remember, HashMap is non intended to proceed entries inwards sorted order, hence if you lot guide hold requirement to e'er proceed entries inwards a detail order, don't usage HashMap instead usage TreeMap or LinkedHashMap. This method should exclusively live used to cater adhoc needs where you lot have a HashMap from around business office of legacy code as well as you lot guide hold to form it starting fourth dimension to procedure entries. If you lot guide hold command of creating the Map initially prefer the correct implementation of Map as well as hence simply HashMap.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures as well as Algorithms: Deep Dive Using Java
Algorithms as well as Data Structures - Part 1 as well as 2
Data Structures inwards Java nine past times Heinz Kabutz


No comments:

Post a Comment