There are multiple way to find third largest element in an Arrays or List in java.
Using Stream.skip() method :-
- First convert Arrays to list using Arrays.asList method
- Now, get Stream data from List using arrayList.stream() method
- Sort arrayList in reverse order using Comparator.reverseOrder() inside Stream.sorted() method
- To arrayList sorted in reverse order, 3rd element in the list will be the third longest element
- We will skip first 2 element which is the longest and 2nd longest element using Stream.skip() method.
- findFirst() method will return 3rd longest String in the arrayList.
- Inside if condition we validate 3rd longest element is not equals to null.
- Now we will print 3rd longest element from get() method.
Using size() method :-
- First we find size of array using length() method.
- Now we sort the elements of the given array using the sort method of the java.util.Arrays class.
- Here array[size-3] is give the 3rd position of element.
- 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 str = arrayList.stream().sorted(Comparator.reverseOrder()).skip(2).findFirst();
if (str != null) {
System.out.println("3rd largest element are :- " + str.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