如何从列表数组中找到最低字段

时间:2014-10-22 02:41:18

标签: java

有人可以告诉我如何从List对象中找到最低的学生ID吗?

我上了学生班:

public class Student{
private int id;
private String name;

..Getter and setters

主要课程:

public class test {

    public static void main(String[] args) {
        Student s1 = new Student(105, "John");
        Student s2 = new Student(101, "Peter");
        Student s3 = new Student(108, "Simon");
        Student s4 = new Student(103, "Jo");

        List<Student> students = new ArrayList<Student>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);

如何从列表中检索最低学生ID?

提前致谢,

2 个答案:

答案 0 :(得分:1)

执行此操作的最快(计算)方式是只需一次通过列表并跟踪最小值:

Integer min = null;
for (Student student : students) {
    if (min == null || student.getId() < min) {
        min = student.getId();
    }
}

然后最低学生ID将存储在min

答案 1 :(得分:1)

Iterator<Student> itr = students.iterator();
Student min_student = itr.next();
Student curr_student;
while (itr.hasNext()) {
    curr_student = itr.next();
    if (curr_student.getId() < min_student.getID()) {
        min_student = curr_student;
    }
}

// min_student这里将是id最小的那个。