另外两个答案都说你不应该或不能改变正在流式传输的对象。据我所知,该指令是不正确的。我怀疑他们混淆了你的规则不应该修改结构体集合的正在流式传输,例如向源列表添加/删除对象。您可以修改内容集合的元素。
流式传输时修改对象
当我们流式传输列表时,在每个 Employee 对象元素上,我们调用 Employee#setSalary 以使用新计算的值进行更新。
使用扩展符号,代码的关键位如下。
当我们流式传输列表时,我们使用 Stream#forEach 在每个元素上运行一些代码。
将 int 字段 salary 乘以 float 类型会得到 float 值。调用 Math.round 会将其转换回 int。
employees
.stream()
.forEach (
( Employee employee ) ->
{
employee.setSalary (
Math.round( employee.getSalary () * 1.5F )
);
}
)
;
这是完整的示例,使用紧凑的表示法。
为方便起见,我们使用 List.of 以文字语法生成不可修改的列表。
List < Employee > employees = List.of(
new Employee( "Alice" , 30 , 3000 ) ,
new Employee( "Bob" , 32 , 3000 ) ,
new Employee( "Carol" , 33 , 5000 )
);
System.out.println( "Before: " + employees );
employees.stream().forEach( employee -> employee.setSalary( Math.round( employee.getSalary() * 1.5F ) ) );
System.out.println( "After: " + employees );
结果:
Before: [Employee[name=Alice, age=30, salary=3000], Employee[name=Bob, age=32, salary=3000], Employee[name=Carol, age=33, salary=5000]]
After: [Employee[name=Alice, age=30, salary=4500], Employee[name=Bob, age=32, salary=4500], Employee[name=Carol, age=33, salary=7500]]
仅供参考,这是上面使用的 Employee 类。没意思。
package work.basil.example.modstream;
import java.util.Objects;
public final class Employee
{
// Member fields.
private String name;
private int age;
private int salary;
// Constructor
public Employee ( String name , int age , int salary )
{
this.name = name;
this.age = age;
this.salary = salary;
}
// Accessors
public String getName ( ) { return name; }
public void setName ( final String name ) { this.name = name; }
public int getAge ( ) { return age; }
public void setAge ( final int age ) { this.age = age; }
public int getSalary ( ) { return salary; }
public void setSalary ( final int salary ) { this.salary = salary; }
// `Object` overrides.
@Override
public boolean equals ( Object obj )
{
if ( obj == this ) { return true; }
if ( obj == null || obj.getClass() != this.getClass() ) { return false; }
var that = ( Employee ) obj;
return Objects.equals( this.name , that.name ) &&
this.age == that.age &&
this.salary == that.salary;
}
@Override
public int hashCode ( )
{
return Objects.hash( name , age , salary );
}
@Override
public String toString ( )
{
return "Employee[" +
"name=" + name + ", " +
"age=" + age + ", " +
"salary=" + salary + ']';
}
}