ストリーム内でオブジェクトを分割できるかどうか疑問に思っています。たとえば、次の場合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
最も美しい解決策ですが、実際にはこれを行うことができない場合があり、ラムダを使用した普遍的な解決策にする必要があります。