Mostly asked coding question in product based company. concepts of maps and there implementation are being asked in many product based companies.
What you will learn in this tutorials ?
1. How to sort map ?
2. How to sort Hash map ?
3. How to Sort map using its key ?
4. How to sort map using its value ?
5. Sort map using its key in ascending or descending order / alphabatically or alphabatically reverse order.
These are the check your map concepts
How to sort hashmap by it's key or value ?
what is hashmap?
Hashmap is a data Structure to store value in for key and values
Map<String, Integer> hmap = new HashMap<String,Integer>
Steps to sort hashmap
Solution in java:-
github link:- DataStructureAndAlgorithms/HashMapMain.java at master · pushpendragupta1993/DataStructureAndAlgorithms (github.com)
Java code to sort hashmap by its value
package com.training; | |
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; | |
public class HashMapMain { | |
public static void main(String args[]) { | |
HashMap<String, String> countryCapitalMap = new HashMap<String, String>(); | |
countryCapitalMap.put("Australia", "Canberra"); | |
countryCapitalMap.put("France", "Paris"); | |
countryCapitalMap.put("Russia", "Moscow"); | |
countryCapitalMap.put("India", "Delhi"); | |
Set<Entry<String, String>> countryCapitalEntrySet = countryCapitalMap.entrySet(); | |
List<Entry<String, String>> entryList = new ArrayList<Entry<String, String>>(countryCapitalEntrySet); | |
Collections.sort(entryList, new Comparator<Entry<String, String>>() { | |
@Override | |
public int compare(Entry<String, String> o1, Entry<String, String> o2) { | |
// sort using value ascending or alphabetically order return o1.getValue().compareTo(o2.getValue()); // sort using value descending or alphabetically revers order return o2.getValue().compareTo(o1.getValue()); // sort using key ascending or alphabetically order return o1.getKey().compareTo(o2.getKey()); // sort using key descending or alphabetically revers order return o1.getKey().compareTo(o2.getKey()); | |
} | |
}); | |
// Using LinkedHashMap to keep entries in sorted order | |
LinkedHashMap<String, String> sortedHashMap = new LinkedHashMap<String, String>(); | |
for (Entry<String, String> entry : entryList) { | |
sortedHashMap.put(entry.getKey(), entry.getValue()); | |
} | |
for (String countryKey : sortedHashMap.keySet()) { | |
System.out.println(countryKey + " -> " + sortedHashMap.get(countryKey)); | |
} | |
} | |
} Video with explanation of the code |
Comments
Post a Comment