Java 8 Stream Collectors groupingBy Example

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

StreamGroupBy.java

package com.ehowtonow.java8;

import java.util.ArrayList;
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);
 }

}

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}


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

  1. Java – DoubleConsumer Interface
  2. Java – LongToDoubleFunction Interface
  3. Java – BiPredicate Interface
  4. Java – IntStream Interface
  5. Java – BinaryOperator Interface
  6. Java 8 Convert Array to Stream
  7. Java – IntPredicate Interface
  8. Java 8 – filter the null values from Stream Example
  9. Java – ToIntBiFunction Interface
  10. Java – IntToLongFunction Interface
  11. Java – ToLongBiFunction Interface
  12. Java – IntConsumer Interface
  13. Java – IntUnaryOperator Interface
  14. Java – ObjDoubleConsumer Interface
  15. Java – UnaryOperator Interface

Be the first to comment

Leave a Reply