Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Sorting HashMap by values [duplicate]

Sorting HashMap by values [duplicate]

August 16, 2021 by James Palmer

Try below code it works fine for me. You can choose both Ascending as well as descending order
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;

public class SortMapByValue
{
public static boolean ASC = true;
public static boolean DESC = false;

public static void main(String[] args)
{

// Creating dummy unsorted map
Map unsortMap = new HashMap();
unsortMap.put(“B”, 55);
unsortMap.put(“A”, 80);
unsortMap.put(“D”, 20);
unsortMap.put(“C”, 70);

System.out.println(“Before sorting……”);
printMap(unsortMap);

System.out.println(“After sorting ascending order……”);
Map sortedMapAsc = sortByComparator(unsortMap, ASC);
printMap(sortedMapAsc);

System.out.println(“After sorting descindeng order……”);
Map sortedMapDesc = sortByComparator(unsortMap, DESC);
printMap(sortedMapDesc);

}

private static Map sortByComparator(Map unsortMap, final boolean order)
{

List> list = new LinkedList>(unsortMap.entrySet());

// Sorting the list based on values
Collections.sort(list, new Comparator>()
{
public int compare(Entry o1,
Entry o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());

}
}
});

// Maintaining insertion order with the help of LinkedList
Map sortedMap = new LinkedHashMap();
for (Entry entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}

return sortedMap;
}

public static void printMap(Map map)
{
for (Entry entry : map.entrySet())
{
System.out.println(“Key : ” + entry.getKey() + ” Value : “+ entry.getValue());
}
}
}

Edit: Version 2

Used new java feature like stream for-each etc
Map will be sorted by keys if values are same

import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

public class SortMapByValue

{
private static boolean ASC = true;
private static boolean DESC = false;
public static void main(String[] args)
{

// Creating dummy unsorted map
Map unsortMap = new HashMap<>();
unsortMap.put(“B”, 55);
unsortMap.put(“A”, 20);
unsortMap.put(“D”, 20);
unsortMap.put(“C”, 70);

System.out.println(“Before sorting……”);
printMap(unsortMap);

System.out.println(“After sorting ascending order……”);
Map sortedMapAsc = sortByValue(unsortMap, ASC);
printMap(sortedMapAsc);

System.out.println(“After sorting descending order……”);
Map sortedMapDesc = sortByValue(unsortMap, DESC);
printMap(sortedMapDesc);
}

private static Map sortByValue(Map unsortMap, final boolean order)
{
List> list = new LinkedList<>(unsortMap.entrySet());

// Sorting the list based on values
list.sort((o1, o2) -> order ? o1.getValue().compareTo(o2.getValue()) == 0
? o1.getKey().compareTo(o2.getKey())
: o1.getValue().compareTo(o2.getValue()) : o2.getValue().compareTo(o1.getValue()) == 0
? o2.getKey().compareTo(o1.getKey())
: o2.getValue().compareTo(o1.getValue()));
return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue, (a, b) -> b, LinkedHashMap::new));

}

private static void printMap(Map map)
{
map.forEach((key, value) -> System.out.println(“Key : ” + key + ” Value : ” + value));
}
}

Assuming Java, you could sort hashmap just like this:
public LinkedHashMap sortHashMapByValues(
HashMap passedMap) {
List mapKeys = new ArrayList<>(passedMap.keySet());
List mapValues = new ArrayList<>(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);

LinkedHashMap sortedMap =
new LinkedHashMap<>();

Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
String val = valueIt.next();
Iterator keyIt = mapKeys.iterator();

while (keyIt.hasNext()) {
Integer key = keyIt.next();
String comp1 = passedMap.get(key);
String comp2 = val;

if (comp1.equals(comp2)) {
keyIt.remove();
sortedMap.put(key, val);
break;
}
}
}
return sortedMap;
}

Just a kick-off example. This way is more useful as it sorts the HashMap and keeps the duplicate values as well.

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in