x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Sort HashMap by key or value Java 8

    Below examples show how to sort HashMap by key or value Java 8

    1) Sort HashMap by key in Java 8

    To sort HashMap by key, you can use Entry comparingByKey() method which will sort the keys by their natural order. To preserve the key order, you need to collect the ouput Map as LinkedHashMap.

    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class SortHashMap {
    
        public static void main(String[] args) {
            Map<String, Integer> map = new HashMap<>();
            map.put("John", 22);
            map.put("Mark", 12);
            map.put("Thomas", 43);
            map.put("James", 34);
            map.put("Edwin", 53);
            map.put("Vinod", 68);
            System.out.println(map);
            Stream<Entry<String, Integer>> stream 
                = map.entrySet().stream().sorted(Map.Entry.comparingByKey());
            LinkedHashMap<String, Integer> sortedMap = stream
                    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(), 
                    (e1, e2) -> e2, LinkedHashMap::new));
            System.out.println(sortedMap);
        }
    }        

    Console Output :

    {Thomas=43, James=34, Edwin=53, John=22, Mark=12, Vinod=68}
    {Edwin=53, James=34, John=22, Mark=12, Thomas=43, Vinod=68}    

    2) Sort HashMap by value in Java 8

    To sort HashMap by value, you can use Entry comparingByValue() method.

    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class SortHashMap {
    
        public static void main(String[] args) {
           Stream<Entry<String, Integer>> stream 
               = map.entrySet().stream().sorted(Map.Entry.comparingByValue());
    
           sortedMap = stream.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(),
               (e1, e2) -> e2, LinkedHashMap::new));
    	   System.out.println(sortedMap);
        }
    
    }

    Console Output :

    {Mark=12, John=22, James=34, Thomas=43, Edwin=53, Vinod=68} 

    3) Sort HashMap by value in Java 8 when value is an Object type

    In case the value is an Object, you can pass Comparator.comparing() in comparingByValue() argument.

    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class SortHashMap {
    
        public static void main(String[] args) {
    
            Map<Integer, Book> bookMap = new HashMap<>();
            bookMap.put(1, new Book("Lord of the Rings", "J. R. R. Tolkien"));
            bookMap.put(2, new Book("Silence of the Lambs", "Thomas Harris"));
            bookMap.put(3, new Book("The Bourne Identity", "Robert Ludlum"));
            bookMap.put(4, new Book("Day of the Jackal", "Frederick Forsyth"));
            System.out.println(map);
    
            Stream<Entry<Integer, Book>> stream = bookMap.entrySet().stream()
                    .sorted(Map.Entry.comparingByValue(Comparator.comparing(Book::getTitle)));
    
            LinkedHashMap<Integer, Book> sortedMap = stream
                    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue(),
                    (e1, e2) -> e2, LinkedHashMap::new));
            System.out.println(sortedMap);
    
        }
    
    }
    
    class Book {
        private final String title;
        private final String author;
    
        public Book(String title, String author) {
            this.title = title;
            this.author = author;
        }
    
        // getter setter remvoed for brevity
    
        @Override
        public String toString() {
            return "Book [title=" + title + ", author=" + author + "]";
        }
    
    }    

    Console Output :

    {1=Book [title=Lord of the Rings, author=J. R. R. Tolkien],
     2=Book [title=Silence of the Lambs, author=Thomas Harris],
     3=Book [title=The Bourne Identity, author=Robert Ludlum],
     4=Book [title=Day of the Jackal, author=Frederick Forsyth]}
    {4=Book [title=Day of the Jackal, author=Frederick Forsyth],
     1=Book [title=Lord of the Rings, author=J. R. R. Tolkien],
     2=Book [title=Silence of the Lambs, author=Thomas Harris],
     3=Book [title=The Bourne Identity, author=Robert Ludlum]}    


    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This