Java 8 stream collect groupByパケット例

7588 ワード

エンティティクラスPeopleは、listに戻るbuildPeopleListメソッドがあり、テストが便利です.
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author: rhyme
 * @date: 2019-09-26 17:31
 * @topic: " "
 * @description: " "
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class People {
    private String name;

    private String character;

    private String sex;

    private int age;

    public static People buildDefault() {
        return People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build();
    }

    public static List buildPeopleList() {
        People p1 = People.builder().name("LuoTianyan").character("optimistic").sex("female").age(24).build();
        People p2 = People.builder().name("Zhang").character("optimistic").sex("female").age(23).build();
        People p3 = People.builder().name("Hu").character("shy").sex("female").age(25).build();
        People p4 = People.builder().name("Y").character("Righteous").sex("male").age(24).build();
        return new ArrayList<>(Arrays.asList(p1, p2, p3, p4));
    }
}

 
テストクラスGroupByTestは、性別グループに基づいて、各性別人数、および各性別マッピング名を統計します.
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;

/**
 * @author: rhyme
 * @date: 2019-10-14 15:59
 * @topic: " "
 * @description: " "
 */
public class GroupByTest {
    private List people;
    private BiConsumer soutKV;
    private Map result;

    @Before
    public void init() {
        people = People.buildPeopleList();
        soutKV = (k, v) -> System.out.println(k + ":" + v);
    }

    @After
    public void soutResult() {
        if (!CollectionUtils.isEmpty(result)) {
            result.forEach(soutKV);
        }
    }

    /**
     *  
     */
    @Test
    public void groupBySex() {
        result = people.stream().collect(
                Collectors.groupingBy(People::getSex)
        );
    }

    /**
     *  
     */
    @Test
    public void groupBySexCount() {
        result = people.stream().collect(
                Collectors.groupingBy(People::getSex, Collectors.counting()
                ));
    }

    /**
     *  name 
     */
    @Test
    public void groupBySexName() {
        result = people.stream().collect(
                Collectors.groupingBy(
                        People::getSex,
                        Collectors.mapping(People::getName, Collectors.toSet())
                ));
    }


}