Find the second-highest number in an ArrayList in Java

In this tutorial, we are going to learn how to find the second-highest number in an ArrayList in Java.

ArrayList is present in java.util package and it provides a dynamic approach for the Arrays. We can perform various operations such as modifying, storing, removing, manipulating Arrays whenever and wherever we want.

Our task is to find the second-highest number in an ArrayList, by simply sorting the numbers in an ArrayList we can achieve our goal. Sort the numbers in ascending order and return the second number from the end.

We can find the second-highest number in an ArrayList by following simple steps as follows:

  • Import java.util package for ArrayList.
  • Create an object of ArrayList.
ArrayList<Integer> arrayList = new ArrayList<Integer>();
  • Add values in ArrayList.
  • Sort the numbers in ArrayList using Collections.sort(ArrayList) method.
Collections.sort(arrayList);
  • Return the second-highest number from the sorted ArrayList.
arrayList.get(arrayList.size()-2);
  • Finally, print the number.

Following is the Java code for our task:

//import package for ArrayList
import java.util.*;
public class ArrayList {
  public static void main(String args[]){
     int temp = 0;
     //create object of ArrayList
     ArrayList<Integer> arrayList = new ArrayList<Integer>(); 
     //add numbers in an ArrayList
     arrayList.add(3);
     arrayList.add(1);
     arrayList.add(6);
     arrayList.add(4);
     arrayList.add(9);
     arrayList.add(8);
     //sort numbers in an ArrayList
     Collections.sort(arrayList);
     //return second highest number from sorted ArrayList
     temp=arrayList.get(arrayList.size()-2);
     System.out.println("Second highest number");
     System.out.println(temp);
  }
}

Output:

Second highest number
8

This is how we can find the second-highest number in an ArrayList in Java. I hope you find this tutorial useful.

Also, read: How to count number of sentences in a text file in Java

Leave a Reply

Your email address will not be published. Required fields are marked *