Member-only story
How to find second highest element from an array in java 8.
In this tutorial, we will learn how to find second highest element from an array in java 8 using stream API.
package com.demo.main;
import java.util.Arrays;
public class FineSecondHighestElementFromArray {
public static void main(String[] args) {
int[] numbers = {5, 13, 41, 88, 99, 77};
Integer SecondHighestElement = Arrays.stream(numbers)
.boxed().sorted(Comparator.reverseOrder())
.skip(1).findFirst().get();
System.out.println(SecondHighestElement);
}
}
First we will convert numbers of array into stream. Arrays.stream(numbers) after that we will call .boxed() method to convert permeative data type into wrapper class. then we need to sort all the elements in descending order then we will call .sorted(Comparator.reverseOrder()) method . now after sorting all the elements in descending order we want to skip first element then will call .skip(1) method. Now our second highest element at first number so now we will call .findFirst() method. findFirst() method will return an optional object then we will call .get() method to get object value.
Watch Video Here :