как найти максимальное значение в ArraList используя лямбда выражение без stream?
Есть ИНТЕРФЕЙС
interface BestStudent{
Student theBest(ArrayList<Student> students);
}
Class Student с Getter setter
public class Student{
String fullName;
int age;
double gpa;
int height;
public Student(String fullName, int age, double gpa, int height) {
this.fullName = fullName;
this.age = age;
this.gpa = gpa;
this.height = height;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
Class StudentsAwards
class StudentAwards{
Student theMostGPA(ArrayList<Student> students){
BestStudent bestStudent=(ArrayList<Student> students1) -> {
double max = students.get(0).getGpa();
return students1.;
};
return bestStudent.theBest(students);
}
В классе StudentAwards написал метод Student theMostGPA(ArrayList<Student> students) то есть он выводит студента из списка у кого самый высокий GPA. Как написать условие?
Ответы (2 шт):
Student theMostGPA(ArrayList<Student> students) {
if (students.isEmpty()) {
return null;
}
List<Student> copy = new ArrayList<>(students);
copy.sort(Comparator.comparingDouble(Student::getGpa).reversed());
return copy.get(0);
}
Я правда не очень понимаю, зачем вам интерфейс BestStudent
Можно использовать Collections::max(Collection<? extends T> coll, Comparator<? super T> comp), который для пустой коллекции выбросит NoSuchElementException.
Тогда можно будет сразу в интерфейсе BestStudent написать статическую реализацию с использованием компаратора Comparator.comparingDouble, и/или добавить метод с компаратором в виде аргумента
interface BestStudent {
static Student theBest(List<Student> students) {
return theBest(students, Comparator.comparingDouble(Student::getGpa));
}
static Student theBest(List<Student> students, Comparator<Student> cmp) {
return Collections.max(students, cmp);
}
}
и вызывать её соответственно так:
class StudentAwards {
Student theMostGPA(List<Student> students) {
return BestStudent.theBest(students);
}
}
Для использования с лямбдой код может выглядеть так:
interface BestStudent {
Student theBest(List<Student> students);
}
class StudentAwards {
Student theMostGPA(List<Student> students) {
BestStudent bs = studs -> Collections.max(studs, Comparator.comparingDouble(Student::getGpa));
return bs.theBest(students);
}
}
Также следует использовать интерфейс List вместо конкретной реализации ArrayList в качестве аргументов методов, и для корректного представления экземпляров Student нужно переопределить метод toString.