我想知道是否可以在 Stream 中拆分对象。例如,为此Employee
:
public class Employee {
String name;
int age;
double salary;
public Employee(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() { return name; }
public int getAge() { return age; }
public double getSalary() { return salary; }
}
我想在流中执行一些操作。为简单起见,让它变成这样(假设我的代码架构不允许将它放在 Employee 类中 - 否则太容易了):
public void someOperationWithEmployee(String name, int age, double salary) {
System.out.format("%s %d %.0f\n", name, age, salary);
}
现在看起来像这样:
Stream.of(new Employee("Adam", 38, 3000), new Employee("John", 19, 2000))
// some conversations go here ...
.forEach(e -> someOperationWithEmployee(e.getName, e.getAge(), e.getSalary));
问题是,是否可以将一些代码放入这样的流中?
Stream.of(new Employee("Adam", 38, 3000), new Employee("John", 19, 2000))
// some conversations go here
.forEach((a, b, c) -> someOperationWithEmployee(a, b, c));
我想达到什么目的?- 我想如果我可以映射一些对象字段,然后像.forEach(this::someOperationWithEmployee)
代码可读性一样处理它们,会稍微提高一些。
2015 年 5 月 14 日更新
毫无疑问,在这种情况下将Employee
对象传递给someOperationWithEmployee
是最漂亮的解决方案,但有时我们在现实生活中无法做到这一点,应该是 lambdas 的通用解决方案。