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.
  • Return the second-highest number from the sorted ArrayList.
  • 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
     //sort numbers in an ArrayList
     //return second highest number from sorted ArrayList
     System.out.println("Second highest number");


Second highest number

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 *