java比较不同ojbects中的归因

时间:2017-02-17 22:56:51

标签: java object

我是一个java初学者,(原谅我的英语不好)我想比较有(名字,分数)的学生对象。并返回得分最高的学生姓名。     我的学生班上有getScore和getName。

public String tallest() {

    //set a defaut value
    int score = 0;
    for(Student student: this.student) {
        // compare which student has highest score
        if(student.getScore() < score) {
            score = student.getScore();
            String name = ((String)student.getName());
        }
    }
    return name;
}

另一个问题是关于如何返回所有学生对象(名称,分数)超过80.

public ArraryList<student>goodStudent<int level> { 
  int level = 80;
  for(Student student: this.student) {
     if(student.getScore > 80) {
     (don't know how to do here >.<)   

   return list;
}

3 个答案:

答案 0 :(得分:3)

public String tallest() {
    return Collections.max(students,
            Comparator.comparingInt(Student::getScore)).getName();
}

public List<Student> goodStudent(int level) {
    return student.stream()
            .filter(s -> s.getScore() > level)
            .collect(Collectors.toList());
}

答案 1 :(得分:0)

对于您的第一个问题,您可以使用java Comparator,构建ScoreComparator,根据其得分对Student进行比较。然后使用Collections.sort(students, new ScoreComprator())对列表进行排序,您可以从中获得最高分(取决于您按升序还是降序排序)

对于第二个问题,您可以实例化另一个ArrayList,然后迭代您的列表students,如果student.getScore() > 80将其添加到新的创建列表中。

答案 2 :(得分:0)

希望这有帮助。任何问题随时都可以问。

import java.util.ArrayList;

class Student{
    private String name;
    private int score;

    public Student(String name, int score){
        this.name = name;
        this.score = score;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Test{

    public static void main(String[] argv) throws Exception {
    Student[] students = {new Student("Jhon", 78), new Student("Kevin", 90), new Student("Max", 100)};

    Student maxScore = GetMaxScore(students);
    System.out.println("Max Score:");
    System.out.println(maxScore.getScore());

    ArrayList<Student> studentsOverVal = GetScoreOverVal(students, 80);
    System.out.println("Students with score over 80: ");
    for(Student student: studentsOverVal) {
       System.out.println(student.getName());
        }

    }

    private static Student GetMaxScore(Student[] students) {
    Student max = students[0];
    for(Student student: students) {
        if(student.getScore() > max.getScore())
            max = student;

        }
    return max;
    }

    private static ArrayList<Student> GetScoreOverVal(Student[] students, int val) {
    ArrayList<Student> overVal = new ArrayList<>();
    for(Student student: students) {
        if(student.getScore() >= val)
            overVal.add(student);
        }
    return overVal;
    }

}