java 如何使用流将对象列表转换为另一个列表对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47796074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:48:50  来源:igfitidea点击:

How to convert list of object to another list object using streams?

javalambdajava-8

提问by Learn Hadoop

The below code snippet, has been implemented without lambda expressions.

下面的代码片段已在没有 lambda 表达式的情况下实现。

How to implement the same functionality using lambda expressions?

如何使用 lambda 表达式实现相同的功能?

public class Java8EmpTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        List<Emp> empInList = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300));
        List<Emp> afterSalayHikeInJava7 = new ArrayList<>();
        // old way
        for (Emp emp : empInList) {
            afterSalayHikeInJava7.add(new Emp(emp.getId(), emp.getSalary() * 100));
        }
        afterSalayHikeInJava7.stream()
                .forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary()));
    }
}

class Emp {
    private int id;
    private int salary;

    public int getId() {
        return id;
    }

    Emp(int id, int salary) {
        this.id = id;
        this.salary = salary;
    }

    public int getSalary() {
        return salary;
    }
}

回答by fxrbfg

Simple use map()method in stream api and collect results:

map()流api中的简单使用方法并收集结果:

  List<Emp> employe = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300));
  List<Emp> employeRise = employe.stream()
                                 .map(emp -> new Emp(emp.getId(), emp.getSalary * 100))
                                 .collect(Collectors.toList());
  employeRise.stream()
            .forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary()));

回答by Eran

map()each Empof the input Listto a new Empand then collect()to a List:

map()每个Emp输入List到一个新的Emp然后collect()到一个List

List<Emp> afterSalayHike = 
    empInList.stream()
             .map(emp->new Emp(emp.getId(), emp.getSalary() * 100))
             .collect(Collectors.toList());