Stream系列(三) FlatMap方法使用

将多维嵌套列表转换为单维列表
Stream系列(三) FlatMap方法使用_第1张图片

EmployeeTestCase.java

package com.example.demo;

import lombok.Data;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.LongStream;
import java.util.stream.Stream;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Log4j2
public class EmployeeTestCase extends BaseTest{

    @Test
    public void flatMap() {
        List employeesAll = listFlat.stream().flatMap(Collection::stream).collect(Collectors.toList());
        assertTrue(employeesAll.size() == 5);

        List employeesAll2 = listFlat.stream().flatMap(employees -> {
            Stream stream = employees.stream();
            return stream;
        }).collect(Collectors.toList());
        assertEquals(employeesAll, employeesAll2);

        List listFlatLong = listFlat.stream()
                .flatMap(employees -> employees.stream())
                .peek(System.out::println)
                .flatMapToLong(employee -> LongStream.of(employee.getId()))
                .peek(System.out::println)
                .boxed()
                .collect(Collectors.toList());
        log.info("listFlatLong:{}", listFlatLong.toString());

        List listFlatLong2 = listFlat.stream()
                .flatMap(employees -> employees.stream())
                .peek(System.out::println)
                .mapToLong(Employee::getId)
                .peek(System.out::println)
                .boxed()
                .collect(Collectors.toList());

        List listFlatName = listFlat.stream().flatMap(employees -> employees.stream())
                .peek(System.out::println)
                .map(employee -> employee.getSalary())
                .peek(System.out::println)
                .collect(Collectors.toList());
    }



}

BaseTest.java

package com.example.demo;

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

public class BaseTest {
    protected static final List list = Arrays.asList(
            new Employee(1, "Alex", 1000),
            new Employee(2, "Michael", 2000),
            new Employee(3, "Jack", 1500),
            new Employee(4, "Owen", 1500),
            new Employee(5, "Denny", 2000));

    protected static final List> listFlat = Arrays.asList(
            Arrays.asList(new Employee(1, "Alex", 1000),
                    new Employee(2, "Michael", 2000)),
            Arrays.asList(new Employee(3, "Jack", 1500),
                    new Employee(4, "Owen", 1500)),
            Arrays.asList(new Employee(5, "Denny", 2000)));
}

关注公众号,坚持每天3分钟学习
Stream系列(三) FlatMap方法使用_第2张图片

你可能感兴趣的:(java,stream,flatmap)