How to get the max element from the arraylist?

Pls help me!I have to get max average grade.How can we take element from arraylist and compare it with another element?

import java.util.ArrayList;  class Student {    String name;   double averageGrade;    public Student(String name, double averageGrade) {     this.name = name;     this.averageGrade = averageGrade;   } }  public class exam2014_07 {    public static void main(String[] args) {     double max = 0;     Student s1 = new Student("Georgi", 5.50);     Student s2 = new Student("Ivan", 5.70);     Student s3 = new Student("Maria", 5.80);      ArrayList<Student> student = new ArrayList<Student>();     student.add(s1);     student.add(s2);     student.add(s3);      for (Student s : student) {       //i need the max grade           if (max > s.averageGrade) {             max = s.averageGrade;             System.out.println("Name: " + s.name + "average grade: " + s.averageGrade);         }        }   } } 
Add Comment
3 Answer(s)

You should check if the grade of the current student is greater than the previous maximum and only print at the end of the loop after you have checked the grades of all the students.

Student best = null; for (Student s : student) {   if (max < s.averageGrade) {       max = s.averageGrade;       best = s;   }    } System.out.println("Name: " + best.name + "average grade: " + best.averageGrade); 
Answered on July 16, 2020.
Add Comment

Since you have max set to 0 and then max > s.averageGrade it will not get an results as 0 is always less than the average. If you flip the greater than to less than; then the way your for loop works will print out all the answers as each average is higher than the previously inserted value.

You can do something like this using java streams to find the max:

Student s = student.stream().max((m1, m2) -> m1.averageGrade.compareTo(m2.averageGrade)).orElse(null); if (s != null)   System.out.println("Name: " + s.name + "average grade: " + s.averageGrade); 

and change your averageGrade from the primitive double to Double so we can take advantage of compareTo

Answered on July 16, 2020.
Add Comment

You can use Stream API, get from the Student object the averageGrade and get the max value in OptionalDouble

OptionalDouble maxOptionalDouble = student.stream().mapToDouble(stud -> stud.averageGrade).max(); if (maxOptionalDouble.isPresent()) {     System.out.println(maxOptionalDouble.getAsDouble()); } 

, Or sort the students based on the averageGrade descending order and get the first one

Comparator<Student> cmp = (stud1, stud2) -> Double.valueOf(stud2.averageGrade)                 .compareTo(Double.valueOf(stud1.averageGrade)); student.sort(cmp); Student std = student.get(0); System.out.println("Name: " + std.name + "average grade: " + std.averageGrade); 
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.