package com.sam.batch.main;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Map.Entry;public class MapSorting {public static void main(String[] args) {MapunsortedMap = new HashMap (); unsortedMap.put("Test1", 3);unsortedMap.put("Test", 3);unsortedMap.put("Test6", 1);unsortedMap.put("Test5", 1);unsortedMap.put("Test3", 1);unsortedMap.put("Test4", 2);System.out.println("unsorted Map");printmap(unsortedMap);System.out.println("sort By Key Map asc");printmap(sortByKey(unsortedMap, true));System.out.println("sort By Key Map desc");printmap(sortByKey(unsortedMap, false));System.out.println("sort By Value Map asc");printmap(sortByValue(unsortedMap, true));System.out.println("sort By Value Map desc");printmap(sortByValue(unsortedMap, false));}static void printmapByIterator(MapduplicateFind) { Iteratorentries = duplicateFind.entrySet().iterator();while (entries.hasNext()) {Map.Entryentry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());}}static void printmap(MapduplicateFind) { for (Map.Entryentry : duplicateFind.entrySet()) { System.out.print(entry.getKey() + "/" + entry.getValue() + " ");}System.out.println();}private static MapsortByKey(Map unorderMap, boolean asc) { List> list =new LinkedList>( unorderMap.entrySet());Collections.sort(list, new Comparator>() { @Overridepublic int compare(Entryo1, Entry o2) { if (asc) {return o1.getKey().compareTo(o2.getKey());} else {return o2.getKey().compareTo(o1.getKey());}}});MapsortedMap = new LinkedHashMap (); for (Entryentry : list) { sortedMap.put(entry.getKey(), entry.getValue());}return sortedMap;}private static MapsortByValue(Map unorderMap, boolean asc) { List> list =new LinkedList>( unorderMap.entrySet());Collections.sort(list, new Comparator>() { @Overridepublic int compare(Entryo1, Entry o2) { if (asc) {return o1.getValue() - o2.getValue();} else {return o2.getValue() - o1.getValue();}}});MapsortedMap = new LinkedHashMap (); for (Entryentry : list) { sortedMap.put(entry.getKey(), entry.getValue());}return sortedMap;}}}
What is the benefit of sorting map manually instead of using TreeMap?
ReplyDeleteTreeMap can't sort by value, only by key.
DeleteIn most of interview, interviewer are asking the same question.