Answers for "sort map by values"

2

Java sort Map by values

//----------------------------------------------------------------------
// in ascending order:
Map<String, Integer> unSortedMap = getUnSortedMap();
         
System.out.println("Unsorted Map : " + unSortedMap);
 
//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<>();
 
unSortedMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue())
    .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
 
System.out.println("Sorted Map   : " + sortedMap);
 
Output:
 
Unsorted Map : {alex=1, charles=4, david=2, brian=5, elle=3}
Sorted Map   : {alex=1, david=2, elle=3, charles=4, brian=5}


//----------------------------------------------------------------------
// in descending order:
Map<String, Integer> unSortedMap = getUnSortedMap();
         
System.out.println("Unsorted Map : " + unSortedMap);
 
//LinkedHashMap preserve the ordering of elements in which they are inserted
LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
 
//Use Comparator.reverseOrder() for reverse ordering
unSortedMap.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 
    .forEachOrdered(x -> reverseSortedMap.put(x.getKey(), x.getValue()));
 
System.out.println("Reverse Sorted Map   : " + reverseSortedMap);
 
Output:
 
Unsorted Map        : {alex=1, charles=4, david=2, brian=5, elle=3}
Reverse Sorted Map  : {brian=5, charles=4, elle=3, david=2, alex=1}
Posted by: Guest on March-06-2020
1

Sort the map by values

Map -- Sort the map by values
Write a method that can sort the Map by values
 
Solution:
public static Map<String, Integer>  sortByValue(Map<String, Integer> map){
List<Entry<String, Integer>> list = new ArrayList(map.entrySet());
list.sort(Entry.comparingByValue());
map = new LinkedHashMap();
for(Entry<String, Integer> each : list) {
map.put(each.getKey(), each.getValue());
}
return map;
}
Posted by: Guest on September-29-2021
1

javascript sort map by value

var mapAsc = new Map([...map.entries()].sort((a,b) => a[0] > b[0]));
Posted by: Guest on December-23-2020
0

javascript sort map by value

var map = new Map();
map.set('2-1', "foo");
map.set('0-1', "bar");
map.set('3-1', "baz");

var mapAsc = new Map([...map.entries()].sort());

console.log(mapAsc)
Posted by: Guest on December-23-2020

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language