Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Thursday, June 17, 2021

Java 8 Stream Group By Count Example

1. Introduction


We will learn how to get the count using the stream group by count technique in this lesson. This is a very helpful way to do aggregated operations with the Java 8 stream grouping API.

Collectors.groupingBy() and Collectors.counting() are used to accomplish the group by count operation.

Let's look at some examples of stream grouping by count.

Java 8 Stream Group By Count Example


2. Java 8 Stream Group By Count


We will start with simple data, which is a list containing duplicate items, and then go on to more complicated data for a better understanding.

Stream Grouping in Java 8 By Count Example:

In the following programme, we have stored a variety of brand names in a list, many of which are repeated. Using the java stream group by count approach, we will now determine how many times each brand is repeated.

We mostly used three functions in this code.

Collectors.groupingBy() - This function requires two arguments and we passed Function.identity() and Collectors.counting().
Function.identity() - Takes each item from the stream and invokes the counting() method. If it finds the same key, it adds one to the current value.
Collectors.counting() - count increments by one if the same key is repeated more than once.

package com.javaprogramto.java8.collectors.groupby.count;

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

/**
 * Stream Group by count examples
 * 
 * @author JavaProgramTo.com
 *
 */

public class GroupByCountExample {

	public static void main(String[] args) {

		List<String> brands = new ArrayList<>();

		brands.add("Apple");
		brands.add("Google");
		brands.add("Nokia");
		brands.add("HTC");
		brands.add("HTC");
		brands.add("Google");
		brands.add("Google");
		brands.add("Google");
		brands.add("Apple");
		brands.add("Apple");
		brands.add("Apple");

		Map<String, Long> countByBrand = brands.stream()
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
		
		System.out.println("Group by count : "+countByBrand);

	}
}
 

Output:
Group by count : {Google=4, Apple=4, HTC=2, Nokia=1}
 

Examine the result of the preceding programme, which displays the unique brand names with a count. This figure indicates the number of times the brand was mentioned in the input list.

You can use the same code to make your scenario functioning.


3. Java 8 Stream Group By Count With filter


Next, take the different types of smartphone models and filter the names to get the brand. Finally get only brand names and then apply the count logic.

Now, using the map() method, filter or transform the model name into brand. Next,  In map() method, we do split the string based on the empty string and take the first value from index 0 which holds the brand name.

We presume that the combination of brand name and model name is always present in the input list. The brand name will always come first, followed by the model name separated by a space.

Look at the output, and it will be the same as the output from the previous section program.
package com.javaprogramto.java8.collectors.groupby.count;

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

/**
 * Stream Group by count examples
 * 
 * @author JavaProgramTo.com
 *
 */

public class GroupByCountFilterExample {

	public static void main(String[] args) {

		List<String> modelNames = new ArrayList<>();

		// adding the model names to the list
		modelNames.add("Apple iphone 12");
		modelNames.add("Google Pixel 5");
		modelNames.add("Nokia 3.1 plus");
		modelNames.add("HTC Desire 21 Pro 5G");
		modelNames.add("HTC Wildfire E1");
		modelNames.add("Google Pixel");
		modelNames.add("Google nexus 6p");
		modelNames.add("Google nexus");
		modelNames.add("Apple iphone 5");
		modelNames.add("Apple iphone 3s");
		modelNames.add("Apple iphone 12 max");

		Map<String, Long> countByBrand = modelNames.stream()
				.map(model -> model.split(" ")[0])
				.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

		System.out.println("Group by brands count : " + countByBrand);

	}

}

 
Output:
Group by brands count : {Google=4, Apple=4, HTC=2, Nokia=1}
 
Let us now remove the brand "HTC" from our groupby outcomes. To filter, use the stream filter() method, which accepts the condition argument as a Predicate. This criteria is used to filter brand names. You can specify any criterion, such as if the brand name length < 5, then just those values will be passed to the group by function, as seen below.
Map<String, Long> countByBrand = modelNames.stream()
		.map(model -> model.split(" ")[0]).filter(brandName -> !brandName.equalsIgnoreCase("HTC") )
		.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println("Group by brands count : " + countByBrand);

// output: Group by brands count : {Google=4, Apple=4, Nokia=1}
 

4. Conclusion


In this post, you've seen how to stream group by count in java 8 with examples.


No comments:

Post a Comment

Please do not add any spam links in the comments section.