Stream系列Map方法使用

Posted javaweibiancheng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Stream系列Map方法使用相关的知识,希望对你有一定的参考价值。

Stream 将List 里面的对象转换为新的对象 

EmployeeTestCase.java

package com.example.demo;
 
import lombok.Data;
import lombok.ToString;
import lombok.extern.log4j.Log4j2;
import org.junit.Test;
 
import java.util.List;
import java.util.stream.Collectors;
 
@Log4j2
public class EmployeeTestCase extends BaseTest{
 
    @Test
    public void map(){
//将Employee 转换 Leader 列表 List
<Leader> leaders = list.stream().filter(employee -> employee.getSalary() == 2000).map(employee -> { Leader leader = new Leader(); leader.setName(employee.getName()); leader.setSalary(employee.getSalary()); return leader; }).peek(System.out::println).collect(Collectors.toList()); } @Data @ToString class Leader{ private String name; private double salary; } }
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)));
        }

 

以上是关于Stream系列Map方法使用的主要内容,如果未能解决你的问题,请参考以下文章

java8 .stream().sorted().filter().map().collect()用法

Java8 Stream流

利用stream对map集合进行过滤

java-stream的map方法中的i++ [重复]

Stream peek 与 map的区别

Stream peek 与 map的区别