// Demo7.java
package com.demo7;
import java.util.ArrayList;
import java.util.Comparator;
public class Demo7 {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Student student1 = new Student();
student1.setId("1001");
student1.setName("张三");
student1.setGender("男");
student1.setAge(18);
list.add(student1);
Student student2 = new Student();
student2.setId("1002");
student2.setName("李四");
student2.setGender("女");
student2.setAge(17);
list.add(student2);
Student student3 = new Student();
student3.setId("1003");
student3.setName("王五");
student3.setGender("男");
student3.setAge(20);
list.add(student3);
Student student4 = new Student();
student4.setId("1004");
student4.setName("牛七");
student4.setGender("女");
student4.setAge(23);
list.add(student4);
Student student5 = new Student();
student5.setId("1005");
student5.setName("马八");
student5.setGender("男");
student5.setAge(28);
list.add(student5);
// 判断张三同学是否存在
boolean exists = list.stream().anyMatch(r -> r.getName() == "张三");
System.out.println(exists ? "张三同学存在。" : "张三同学不存在。");
// 按年龄排序
list.sort(new Comparator<Student>() {
@Override
public int compare(Student arg0, Student arg1) {
return new Integer(arg0.getAge()).compareTo(new Integer(arg1.getAge()));
}
});
for(Student item : list) {
System.out.println(item.getId() + "\t" + item.getName() + "\t" + item.getGender() + "\t" + item.getAge());
}
}
}// Student.java
package com.demo7;
// 学生类
public class Student {
// 学号
private String id;
// 姓名
private String name;
// 性别
private String gender;
// 年龄
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
温馨提示:答案为网友推荐,仅供参考