Java统一设置List对象中某个字段值
在Java编程中,我们常常需要对List对象中的某个字段值进行统一设置。这种操作可以帮助我们快速地批量修改对象中的某个属性,提高程序的效率。本文将通过代码示例来演示如何使用Java实现这一功能。
问题描述
假设我们有一个Person
类,包含姓名和年龄两个属性。现在我们有一个List<Person>
对象,需要将其中所有人的年龄统一设置为30岁。如何实现这一功能呢?
解决方案
我们可以通过遍历List对象,逐个修改每个Person对象的年龄属性来实现统一设置。下面是一个示例代码:
import java.util.List;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = List.of(new Person("Alice", 25), new Person("Bob", 28), new Person("Charlie", 22));
System.out.println("Before setting: ");
people.forEach(System.out::println);
// 统一设置年龄为30岁
people.forEach(person -> person.setAge(30));
System.out.println("After setting: ");
people.forEach(System.out::println);
}
}
在上面的代码中,我们首先定义了一个Person
类,包含姓名和年