Java 8 Stream Sort a Map

By Yashwant Chavan, Views 20242, Last updated on 05-Nov-2016

In this tutorial you will learn how to Sort a Map using Java 8 Stream api. I am using Map to store data about top populous cities in the world in the form of key and value. We will cover different examples to sort map using keys, values, sorting in reverse order and find out top two populous cities.

tags java

Refer below steps.

  • Define Map <String, Integer> to store data of top populous cities in the world in the form of key and value pair.
  • Sort key - Use Stream.sorted() to sort elements base on Comparator.

    • comparingByKey() - Returns a comparator that compares Map.Entry in natural order on key.
  • Sort key in reversed order

    • comparingByKey() - Returns a comparator that compares Map.Entry in natural order on key.
    • comparingByKey().reversed() - Returns a comparator that imposes the reverse ordering of this comparator.
  • Sort by value

    • comparingByValue() - Returns a comparator that compares Map.Entry in natural order on value.
  • Apply limit

    • comparingByKey() - Returns a comparator that compares Map.Entry in natural order on key.
    • comparingByKey().reversed() - Returns a comparator that imposes the reverse ordering of this comparator.
    • limit(long) - Returns specified number of the elements of this stream.
  • Print the result using forEachOrdered() method.

Sort map by key

cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByKey())
    .forEachOrdered(e -> System.out.println(e.getKey()));

Sort key in reversed order

cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByKey().reversed())
    .forEachOrdered(e -> System.out.println(e.getKey()));

Sort map by value

cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByValue())
    .forEachOrdered(e -> System.out.println(e.getValue()));

Find top two populous cities

cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByValue().reversed())
    .limit(2)
    .forEachOrdered(e -> System.out.println(e));

Sort Map full Example

package com.technicalkeeda.app;

import java.util.HashMap;
import java.util.Map;

public class Java8StreamSortMap {

    public static void main(String[] args) {

        Map <String, Integer> cities = new HashMap <> ();

        cities.put("Shanghai", 24256800);
        cities.put("Karachi", 23500000);
        cities.put("Beijing", 21516000);
        cities.put("Delhi", 16349831);
        cities.put("Lagos", 16060303);
        cities.put("Tianjin", 15200000);

        System.out.println("Sort by key:-");
        cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByKey())
            .forEachOrdered(e -> System.out.println(e.getKey()));

        System.out.println("\nSort by key in reversed order:-");
        cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByKey().reversed())
            .forEachOrdered(e -> System.out.println(e.getKey()));

        System.out.println("\nSort by value:-");
        cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByValue())
            .forEachOrdered(e -> System.out.println(e.getValue()));

        System.out.println("\nSort by value with limit option (Top two populous cities in the world):- ");
        cities.entrySet().stream().sorted(Map.Entry. <String, Integer> comparingByValue().reversed())
            .limit(2)
            .forEachOrdered(e -> System.out.println(e));

    }
}

output

Sort by key:-
Beijing
Delhi
Karachi
Lagos
Shanghai
Tianjin

Sort by key in reversed order:-
Tianjin
Shanghai
Lagos
Karachi
Delhi
Beijing

Sort by value:-
15200000
16060303
16349831
21516000
23500000
24256800

Sort by value with limit option (Top two populous cities in the world):- 
Shanghai=24256800
Karachi=23500000
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]