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

时间:2017-12-13 14:58:10

标签: java lambda java-8

以下代码片段已实现,没有lambda表达式。

如何使用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;
    }
}

2 个答案:

答案 0 :(得分:5)

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

  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()));

答案 1 :(得分:4)

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

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