Wednesday 30 August 2017

How to sort the map using sorted method of Java 8 Stream | Streams in Java 8


Click here to watch in Youtube :
https://www.youtube.com/watch?v=_q1y8mE44aQ&list=UUhwKlOVR041tngjerWxVccw

StreamSortedDemo.java
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class StreamSortedDemo
{
    public static void main(String[] args)
    {

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Ball");
        map.put(2, "Cat");
        map.put(3, "Apple");
        map.put(4, "Dog");

        /*
         * sorted() : It returns a stream sorted with given
         * Comparator.
         */
        System.out.println("---Sort by Map Value---");
        map.entrySet().stream()
                .sorted(Comparator.comparing(Map.Entry::getValue))
                .forEach(e -> System.out.println("Key: " + e.getKey()
                        + ", Value: " + e.getValue()));
    }
}
Output
---Sort by Map Value---
Key: 3, Value: Apple
Key: 1, Value: Ball
Key: 2, Value: Cat
Key: 4, Value: Dog

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_Map_Sorted_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_Map_Sorted_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/07d37f967453de17efa70af5825dc03ae2d5a7c0/BasicJava/StreamDemo_Map_Sorted_App/?at=master

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment