Home » Java stream group by field

Java stream group by field

  • by
Java stream group by field

1. Overview

In this article, we will learn to use the group by function of Java Stream using a field. To learn more about other Java stream topics, refer to these articles.

2. Java stream API

The Stream API introduced in Java 8 is used to process a collection of objects. It represents a sequence of objects and provides various utility methods to produce the desired result.

2.1. Java Stream group by field

The Collectors factory methods groupingBy() and groupingByConcurrent() allow us to group a collection based on certain fields and store the results in a Map object.

A groupingBy returns a Collector implementing a cascaded “group by” operation on input elements, grouping elements according to a classification function, and then performing a reduction operation on the values associated with the provided key using the specified downstream Collector.

A downstream reduce function is optional. For instance, counting is a reduction operation that helps to count the number of occurrences of the specified key and we will see an example in section 2.2.

A classifier function maps the input elements to keys.

In the below example, we are using the groupingBy function to group the collection based on the name field. It returns the result as a Map. This groupingBy variant takes only the classifier function as input. This classifier function suggests using the name field as a key for grouping.

  @Test
  public void testCount() {
    List<Language> list = Arrays.asList(
            new Language("Java"),
            new Language("Java"),
            new Language("Python"),
            new Language("Java"),
            new Language("Cpp"),
            new Language("Python"),
            new Language("Cpp"));
// public static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)
    Map<String, List<Language>> sortedList = list.stream().collect(Collectors.groupingBy(Language::getName));
    System.out.println(sortedList);
  }

If you execute the above code, you get the below result.

{Java=[Language{name='Java'}, Language{name='Java'}, Language{name='Java'}], Cpp=[Language{name='Cpp'}, Language{name='Cpp'}], Python=[Language{name='Python'}, Language{name='Python'}]}

2.2. Java stream group by a string collection

You can also group a collection of String objects as below:

@Test
public void testCount() {
    List<String> list = Arrays.asList("Java", "Java", "CPP", "Python", "CPP", "Kotlin");
    Map<String, List<String>> sortedList = list.stream().collect(Collectors.groupingBy(temp -> temp));
    System.out.println(sortedList);
    // {Java=[Java, Java], CPP=[CPP, CPP], Kotlin=[Kotlin], Python=[Python]}
}

You can also use the above strategy to count the number of occurrences of a String in the list. Here, we are combining the reduction operation counting along with the classifier function.

@Test
  public void testCount() {
    List<String> list = Arrays.asList("Java", "Java", "CPP", "Python", "CPP", "Kotlin");
// public static <T,K,A,D> Collector<T,?,Map<K,D>> groupingBy(Function<? super T,? extends K> classifier,
//                                                          Collector<? super T,A,D> downstream)
    Map<String, Long> sortedList = list.stream().collect(Collectors.groupingBy(temp -> temp, Collectors.counting()));
    System.out.println(sortedList);
  }
{Java=2, CPP=2, Kotlin=1, Python=1}

3. Conclusion

To sum up, we have learned the Java Stream group by function. There are several other ways to use group by function of the Java Stream API.

Leave a Reply

Your email address will not be published.