Answers for "sort treemap by value in descending order java"

2

java treemap sort by value in reverse

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}
Posted by: Guest on March-01-2020
2

TreeMap descendingKeySet() method in java

import java.util.NavigableSet;
import java.util.TreeMap;
public class TreeMapDescendingKeySetMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(63, "banana");
      tm.put(56, "watermelon");
      tm.put(35, "orange");
      tm.put(83, "apple");
      tm.put(65, "pineapple");
      // put values in NavigableSet
      NavigableSet ns = tm.descendingKeySet();
      System.out.println("TreeMap values using descendingKeySet() method: ");
      System.out.println("NavigableSet values: " + ns);
   }
}
Posted by: Guest on October-28-2020

Code answers related to "sort treemap by value in descending order java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language