In Java, there are multiple ways to find third largest element in an array or list. In this example, we will see two approaches:
- Using Java 8 Stream API with
skip() - Using
Arrays.sort()and array indexing
Both methods are simple and useful for interview preparation as well as coding practice.
Using Stream.skip() method :-
- Convert the array elements into a list using Arrays.asList()
- Convert the list into a stream using stream() method
- Sort the list in descending order using Comparator.reverseOrder()
- Skip the first two elements using skip(2)
- Use findFirst() to get the third largest element
- Inside if condition we validate 3rd largest element is present or not.
- Now we will print 3rd longest element from get() method.
Using Arrays.sort() method :-
- Find the size of the array using the length property
- Sort the array using Arrays.sort().
- Access the third largest element using array[size – 3]
- Now we will print 3rd longest element.
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class ThirdLargestElement {
public static void main(String[] args) {
List arrayList = Arrays.asList(220, 2, 16, 238, 185);
// Stream.skip() method
Optional thirdLargest = arrayList.stream()
.sorted(Comparator.reverseOrder())
.skip(2).findFirst();
if (thirdLargest.isPresent()) {
System.out.println("3rd largest element are :- " + thirdLargest.get());
}
// Using size method
int array[] = {220, 2, 16, 238, 185};
int size = array.length;
Arrays.sort(array);
int in = array[size - 3];
System.out.println("3rd largest element are :" + in);
}
}
Output :-
3rd largest element are :- 185
3rd largest element are :185