Saturday , April 29 2017
Home / java8 / How to sort a Map using Java8

How to sort a Map using Java8

I this  tutorials, I am going to show you how to sort a Map using Java 8 features.

Sort a Map using Java8 :

We can sort a map by two ways: Sort by key and value.

Sort by key :

package com.onlinetutorialspoint.java8;

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

public class Java8_SortaMap {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Maths", 95);
        marks.put("Chemistry", 84);
        marks.put("Physics", 92);
        marks.put("Languages", 94);
        sortByKey(marks);
    }

    public static void sortByKey(Map<String, Integer> marks) {
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        marks.entrySet().stream()
         .sorted(Map.Entry.<String, Integer>comparingByKey())
         .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        System.out.println(sortedMap);
    }
}
{Chemistry=84, Languages=94, Maths=95, Physics=92}

Sort by Value :

package com.onlinetutorialspoint.java8;

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

public class Java8_SortaMap {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Maths", 95);
        marks.put("Chemistry", 84);
        marks.put("Physics", 92);
        marks.put("Languages", 94);
        sortByValue(marks);
    }

    public static void sortByValue(Map<String, Integer> marks) {
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        marks.entrySet().stream()
        .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
        .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        System.out.println(sortedMap);
    }
}

{Maths=95, Languages=94, Physics=92, Chemistry=84}

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Java 8 Read File Line By Line Example

In this tutorials, I am going to show you how to read a File line …

Leave a Reply

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