Stream系列(三) FlatMap方法使用

panwenhai

将多维嵌套列表转换为单维列表
image

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<Employee> employeesAll = listFlat.stream().flatMap(Collection::stream).collect(Collectors.toList());
        assertTrue(employeesAll.size() == 5);

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

        List<Long> 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<Long> listFlatLong2 = listFlat.stream()
                .flatMap(employees -> employees.stream())
                .peek(System.out::println)
                .mapToLong(Employee::getId)
                .peek(System.out::println)
                .boxed()
                .collect(Collectors.toList());

        List<Double> 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<Employee> 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<List<Employee>> 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分钟学习
image

阅读 3.5k

爱生活,也爱这世界

10 声望
11 粉丝
0 条评论

爱生活,也爱这世界

10 声望
11 粉丝
文章目录
宣传栏