A:遍历集合遍历输出。
B:求出年龄最大的学生,然后将该对象的姓名变为:葫芦娃。
代码示例:
package ;public class Student {private String name;private int age;private String sex;@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", sex='" + sex + '\'' +'}';}public Student(String name, int age, String sex) {this.name = name;this.age = age;this.sex = sex;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}}
package ;import java.util.ArrayList;import java.util.List;import java.util.Optional;public class Demo {public static void main(String[] args) {List<Student> list = new ArrayList<Student>();//添加元素到集合add(list);//遍历集合并打印ergodicPrint(list);//修改年龄最大的学生姓名为葫芦娃changeMaxAgeName(list);System.out.println("-------------");//遍历集合并打印ergodicPrint(list);}private static void changeMaxAgeName(List<Student> list) {Optional<Student> op = list.stream().sorted((s1, s2) -> (s2.getAge()-s1.getAge())).findFirst();Student student = op.get();student.setName("葫芦娃");}private static void ergodicPrint(List<Student> list) {for(int i = 0;i<list.size();i++){System.out.println(list.get(i));}}private static void add(List<Student> list) {list.add(new Student("xiaochen",20,"男"));list.add(new Student("xiaoli",25,"女"));list.add(new Student("xiaowang",22,"男"));}}