user2977165
user2977165

Reputation: 47

Trying to print the maximum value of the arraylist in java

I've sorted my arraylist in descending order and now I want to print the max value. the arraylist contains a student's name and their grade. I want to print the name of the student with the highest grade. I don't need to print their grade. Just the name. this is my code

public void printStudent(){

    Collections.sort(studentList);
    Collections.reverse(studentList);
    System.out.println("Best student is: ");
    for (Student s: studentList){
        System.out.println(s.toString());
    }
}

Right now this prints the entire list of students and their grades however I just want to print the name of the student with the highest grade and I've tried many things but can't seem to get it to work. Thanks!

Upvotes: 0

Views: 437

Answers (4)

Stephen C
Stephen C

Reputation: 718788

Hint:

  • If you hare sorted a list into ascending order, where is the largest element?

  • If you then reverse the list, where is the largest element now?

  • How do you get the Nth element of a list? (Meta-hint ... read the javadoc!)

Upvotes: 5

Lakatos Gyula
Lakatos Gyula

Reputation: 4160

Use Collections.max and not sorting.

Upvotes: 3

Joakim Palmkvist
Joakim Palmkvist

Reputation: 540

How is your Combarable interface setup? Collections.sort is based on this.

So either you can print customerList.get(customerList.size() - 1) to print the last index in your list. Or you can print customerList.get(0)

But as I said: This depends on how you compare Customer against each other.

Upvotes: 0

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

You already sorted the Customer in reverse order then the highest grade should be in the first position of your collection.

Do like below.

Customer c = customerList.get(0); // getting the first elementt
System.out.println(c.toString());

Upvotes: 0

Related Questions