Table of contents
1.
Introduction
2.
Find 2nd Largest Number in Array using Arrays
2.1.
Java
3.
Find 2nd Largest Number in Array using Collections
3.1.
Java
4.
Frequently Asked Questions
4.1.
What if there are duplicate elements in the array?
4.2.
Can these approaches be used with arrays of other data types?
4.3.
What is the time complexity of these approaches?
5.
Conclusion
Last Updated: Aug 24, 2024
Easy

Java Program to Find Second Largest Element in an Array

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

An array is a linear collection of values stored at contiguous memory locations. Array stores homogeneous values(similar data type values).They are a one of the most important fundamental data structure in Java for storing and manipulating elements.When we work on array, the common problem we get to check our understanding and skill is finding the second largest element. This is a very good exercise to implement our learning. 

Java Program to Find Second Largest Element in an Array

In this article we will see both of the two methods of finding the second largest element like using array and collections.

Find 2nd Largest Number in Array using Arrays

One approach to finding the second largest element in an array is by using basic array manipulation techniques. 

Let’s see how we can do it:
 

1. Initialize two variables, `largest` and `secondLargest`, to store the largest and second largest elements respectively. Set `largest` to the smallest possible value (e.g., `Integer.MIN_VALUE`) and `secondLargest` to the same value.
 

2. Iterate through the array using a loop. For each element:

  • If the current element is greater than `largest`, update `secondLargest` to the value of `largest` and update `largest` to the current element.
     
  • If the current element is greater than `secondLargest` but not equal to `largest`, update `secondLargest` to the current element.
     

3. After the loop ends, `secondLargest` will hold the second largest element in the array.
 

Let’s see the code implementation in Java:

  • Java

Java

public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 4, 45, 99, 99, 67};
int secondLargest = findSecondLargest(arr);

if (secondLargest == Integer.MIN_VALUE) {
System.out.println("There is no second largest element.");
} else {
System.out.println("The second largest element is: " + secondLargest);
}
}

public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;

for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

return secondLargest;
}
}
You can also try this code with Online Java Compiler
Run Code


Output

The second largest element is: 67


Given the array {10, 20, 4, 45, 99, 99, 67}, the program would return the second largest element. It efficiently finds the second largest element in a single pass through the array.

Find 2nd Largest Number in Array using Collections

Another approach to finding the second largest element in an array is by taking advantage of the Java Collections framework. 

Let’s see how we can do it:
 

1. Convert the array to an ArrayList using the `Arrays.asList()` method. This allows us to use the collections framework methods.
 

2. Remove duplicates from the ArrayList by converting it to a HashSet and then back to an ArrayList. This step is optional but ensures that we handle duplicate elements correctly.
 

3. Sort the ArrayList in descending order using the `Collections.sort()` method with a custom comparator.
 

4. Retrieve the second element from the sorted ArrayList, which will be the second largest element.
 

Let’s see the code implementation in Java:

  • Java

Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;

public class Main {
public static void main(String[] args) {
Integer[] arr = {10, 20, 4, 45, 99, 99, 67};
int secondLargest = findSecondLargestUsingCollections(arr);

System.out.println("The second largest element is: " + secondLargest);
}

public static int findSecondLargestUsingCollections(Integer[] arr) {
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(arr));

// Remove duplicates
list = new ArrayList<>(new HashSet<>(list));

// Sort the list in descending order
Collections.sort(list, Collections.reverseOrder());

// Return the second largest element
return list.get(1);
}
}
You can also try this code with Online Java Compiler
Run Code

Output

The second largest element is: 67


Given the array {10, 20, 4, 45, 99, 99, 67}, the program would return the second largest element.  It utilizes the collections framework to simplify the process. The steps are as follows:

1. Convert the array to an ArrayList using `Arrays.asList()`.
 

2. Remove duplicates by converting the ArrayList to a HashSet and then back to an ArrayList.
 

3. Sort the ArrayList in descending order using `Collections.sort()` with `Collections.reverseOrder()` comparator.
 

4. Retrieve the second element from the sorted ArrayList using `list.get(1)`.


Note: With collections method, we can achieve the desired result with just a few lines of code. However, this approach may have a slightly higher time complexity compared to the previous approach due to the sorting step.

Frequently Asked Questions

What if there are duplicate elements in the array?

If there are duplicate elements in the array, both approaches will still find the second largest element correctly. The first approach using arrays will skip duplicates, while the second approach using collections removes duplicates before finding the second largest element.

Can these approaches be used with arrays of other data types?

Yes, these approaches can be adapted to work with arrays of other comparable data types, such as floating-point numbers or characters. The logic remains the same, but the data types and comparisons may need to be adjusted accordingly.

What is the time complexity of these approaches?

The first approach using arrays has a time complexity of O(n), where n is the size of the array, as it iterates through the array once. The second approach using collections has a time complexity of O(n log n) due to the sorting step. However, the second approach may be more convenient and readable in certain scenarios.

Conclusion

In this article, we learned how to find the second largest element in an array using Java. We discussed two different approaches: one using basic array manipulation and another using the Java Collections framework. Both approaches provide efficient solutions to the problem, with the array approach having a better time complexity.

You can also check out our other blogs on Code360.

Live masterclass