Java – Group List elements

The groupingBy(classifier, downstream) collector allows the collection of Stream elements into a Map by classifying each element in a group and performing a downstream operation on the elements classified in the same group.

 

package com.pwn.stream;

import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FrequencyMap {

	public static void main(String[] args) {
		Stream.of("apple", "orange", "banana", "apple", "mango",
				"kiwi", "mango", "apple")
				.collect(Collectors.groupingBy(Function.identity(),
						Collectors.counting()))
				.entrySet().forEach(System.out::println);

	}

}
banana=1
orange=1
apple=3
kiwi=1
mango=2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s