Write a Program to find the second largest number in array in Java

Hey guys in this article, we will discuss finding the second largest number in array using Java. First, let’s look at the solution then I will explain the solution.



Watch the Video


Solution


public class SecondHighestNumber {
	
	public static void main(String[] args) {
		
		int[] randomNumbers = {1, 5, 4, 2, 8, 1, 8, 9,9};
		
		SortedSet<Integer> set = new TreeSet<Integer>();
		for(Integer i : randomNumbers) {
			set.add(i);
		}
		set.remove(set.last());
		System.out.println(set.last());

	}
	
}

Output:

8

We will use the Java Collection framework to find the second largest number in an array.

  • We all know that Set interface does not allow duplicates, so we will use TreeSet to remove the duplicates from the array.
  • Also TreeSet is the implementation of the SortedSet, it will sort the items in the Ascending order by default.
  • Once the list is sorted, now we can remove the highest element from the list by calling the list.remove(list.last()) method.
  • Now the largest number is removed from the list, now the second-largest number is the last item on the list.
  • We can get the second-largest number by calling list.last() the method




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply