Answers for "how to sort a treemap by value in 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
0

treemap get order java

// Implement tree map in Java

import java.util.SortedMap;
import java.util.TreeMap;

public class CreateTreeMapExample {
    public static void main(String[] args) {
        // Creating a TreeMap
        SortedMap<String, String> fileExtensions  = new TreeMap<>();

        // Adding new key-value pairs to a TreeMap
        fileExtensions.put("python", ".py");
        fileExtensions.put("c++", ".cpp");
        fileExtensions.put("kotlin", ".kt");
        fileExtensions.put("golang", ".go");
        fileExtensions.put("java", ".java");

        // Printing the TreeMap (Output will be sorted based on keys)
        System.out.println(fileExtensions);
    }

}
Posted by: Guest on May-09-2020

Code answers related to "how to sort a treemap by value in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language