See the complete test code at the end of this article.

The test data is the four employee object instances in the List:

Employees are grouped according to their cities:

The results were divided into three groups:

The first group of employees in Shanghai:

The second group of employees in Chengdu:

Number of employees in each group:



Divide the employees into groups, with those who scored more than 101 in one group and those who scored less than or equal to 101 in the other group:

Grouping results:



package java8;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import java.util.stream.Collectors;

class Employee {
	private String city;
	private String name;
	private int score;
	
	public Employee(String name, String city, int score){
		this.city = city;
		this.name = name;
		this.score = score;
	}
	
	public String getCity(a){
		System.out.println("city: " + this.city);
		return this.city;
	}
	
	public String getName(a) {
		return this.name;
	}
	
	public int getScore(a) {
		return this.score;
	}
	
	@Override
    public String toString(a) {
        return String.format("Employee: " + this.name + " city: " + this.city); }}class Person {
    private String name;
    private int age;
 
    Person(String name, int age) {
 
        this.name = name;
        this.age = age;
    }
 
    @Override
    public String toString(a) {
        return String.format("Person{name='%s', age=%d}", name, age); }}// Jerry 2016-01-15 20:51PM ? Used mostly for extends Generic type, which accepts all Object sub classes
public class StreamTest {
	private static void printMap(Map<? extends Object, ? extends Object> map) {
		 for(Entry<? extends Object, ? extends Object> entry:map.entrySet()) {
			    System.out.println("key = " + entry.getKey() + " , Value = "+ entry.getValue()); }}public static void main(String[] args) {
		ArrayList<Employee> employees = new ArrayList<Employee>();
		employees.add(new Employee("A"."Shanghai".100));
		employees.add(new Employee("B"."Chengdu".101));
		employees.add(new Employee("C"."Shenzhen".102));
		employees.add(new Employee("D"."Chengdu".104));
		
		// group by City
		Map<String, List<Employee>> employeesByCity =
				employees.stream().collect( Collectors.groupingBy(Employee::getCity));
		// default void forEach(Consumer
       action) {
		for(Map.Entry<String, List<Employee>> entry:employeesByCity.entrySet()) {
		    System.out.println("key= " + entry.getKey() + " , Value = " + entry.getValue());
		    entry.getValue().forEach(System.out::println);
		 }
		 
		 // 2016-01-15 20:37PM 
		 Consumer<Employee> aa = a -> { System.out.println("Employee: " + a.getName() + ":" +  a.getScore()); };
		 List<Employee> chengduEmployee = employeesByCity.get("Chengdu");
		 chengduEmployee.forEach(aa);
		 
		 // test for counting
		 Map<String, Long> employeesByCity2 = 
				 employees.stream().collect( Collectors.groupingBy(Employee::getCity, Collectors.counting()));
		 printMap(employeesByCity2);
		
		 // calculate average score
		 Map<String, Double> employeesByCity3 = 
				 employees.stream().collect( Collectors.groupingBy(Employee::getCity,
						 Collectors.averagingInt(Employee::getScore)));
		 
		 printMap(employeesByCity3);
		/*Stream
      
        people = Stream.of(new Person("Paul", 24), new Person("Mark", 30), new Person("Will", 28)); Map
       
        > peopleByAge = people.collect(groupingBy(p -> p.age, mapping((Person p) -> p.name, toList()))); System.out.println(peopleByAge); * /
       ,>
      
		 
		 /* * Partitioning is a special grouping, and the resulting map contains at least two distinct groupings -- one true and one false. * For example, if you want to find the best employees, you can divide all employees into two groups, one selling more than N and the other selling less than N, using the partitioningBy collector: */
		 System.out.println("partition result");
		 Map<Boolean, List<Employee>> partitioned =
				 employees.stream().collect(Collectors.partitioningBy(e -> e.getScore() > 101));
		 printMap(partitioned);
		 
		 /* * You can also pass the groupingBy collector to the partitioningBy collector to combine partitioning and grouping. For example, you could count the number of employees in each city in each district:  Map
      
       > result = employees.stream().collect(partitioningBy(e -> e.getNumSales() > 150, groupingBy(Employee::getCity, counting()))); This generates a secondary Map: {false={London=1}, true={New York=1, Hong Kong=1, London=1}} */
      ,>}}Copy the code

For more of Jerry’s original articles, please follow the public account “Wang Zixi “: