How to sort a Map using Java8

By | 2017-04-09T15:16:19+00:00 April 3rd, 2017|java8|0 Comments

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);
    }
}

[box type=”success” align=”alignleft” class=”” width=”100%”]
{Chemistry=84, Languages=94, Maths=95, Physics=92}

[/box]
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);
    }
}

[box type="success" align="alignleft" class="" width="100%"]
{Maths=95, Languages=94, Physics=92, Chemistry=84}
[/box]

About the Author:

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+ ,

Leave A Comment