We are moved to new domain
Click -> www.ehowtonow.com
Sunday, 25 June 2017

Java 8 Stream Collectors groupingBy with sort Example

In this article we are going to see about Java 8 Stream Collectors  groupingBy with sort example program.

StreamGroupBy.java

package com.javatutorialcorner.java8;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class StreamGroupBy {

 public static void main(String[] args) {
  List batsmanRanking = new ArrayList<>();
  batsmanRanking.add("Virat Kohli");
  batsmanRanking.add("AB de Villiers");
  batsmanRanking.add("David Warner");
  batsmanRanking.add("Joe Root");
  batsmanRanking.add("Kane Williamson");
  batsmanRanking.add("Quinton de Kock");
  batsmanRanking.add("AB de Villiers");
  batsmanRanking.add("Faf du Plessis");
  batsmanRanking.add("Virat Kohli");
  batsmanRanking.add("Babar Azam");
  batsmanRanking.add("Quinton de Kock");
  batsmanRanking.add("Martin Guptill");
  batsmanRanking.add("Shikhar Dhawan");
  batsmanRanking.add("AB de Villiers");
  batsmanRanking.add("Virat Kohli");
  batsmanRanking.add("Faf du Plessis");

  System.out.println("Java 8 Group by a List and display the total count.");

  Map result = batsmanRanking.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

  System.out.println(result);
  
  System.out.println("Java 8 Group by a List and display the total count with sorted order.");
  Map sortedResult = new LinkedHashMap<>();

  // Sort a map and add to sortedResult
  result.entrySet().stream().sorted(Map.Entry.comparingByValue().reversed())
    .forEachOrdered(e -> sortedResult.put(e.getKey(), e.getValue()));

  System.out.println(sortedResult);
 }

}

Output
Java 8 Group by a List and display the total count.
{Faf du Plessis=2, Virat Kohli=3, Martin Guptill=1, Babar Azam=1, Quinton de Kock=2, Kane Williamson=1, AB de Villiers=3, Joe Root=1, Shikhar Dhawan=1, David Warner=1}
Java 8 Group by a List and display the total count with sorted order.
{Virat Kohli=3, AB de Villiers=3, Faf du Plessis=2, Quinton de Kock=2, Martin Guptill=1, Babar Azam=1, Kane Williamson=1, Joe Root=1, Shikhar Dhawan=1, David Warner=1}




Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: Java 8 Stream Collectors groupingBy with sort Example Rating: 5 Reviewed By: eHowToNow