In  this tutorial, we will see “How to find the second largest number in an array using Java 8?”

find second largest number in an array using java 8 stream

Java 8 – How to find the Second Largest Number in an Array? – Simplest Examples Share on X

Java 8 1st method:

/**
 * Using Skip method of Java 8 Stream, Find the second largest number in an array
 * @author Deepak Verma
 *
 */

import java.util.Arrays;
import java.util.stream.IntStream;

public class Find_Second_Largest_Number_In_Array_Java8Stream_Example1 {

	public static void main(String args[]) {

		int[] numbers = {3,15,29,18,73,64};
		
		// Get a stream of the numbers
		IntStream stream = Arrays.stream(numbers);
		
		int secondLargest = stream.sorted()
					              .skip(numbers.length - 2)
					              .findFirst()
					              .getAsInt();
		
		System.out.println("Second Largest Number in the Array is: "+secondLargest);

	}
}

 

Output:

Second Largest Number in the Array is: 64

check if text or string present in a file using java 8

In above example, It first sorts the array, then skips the last element (the largest one) using skip(arr.length - 2), and finally finds the first element in the remaining stream, which is the second largest number.

Java 8 2nd method:

/**
 * Using Skip and Limit method of Java 8 Stream, Find the second largest number in an array
 * @author Deepak Verma
 *
 */

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class Find_Second_Largest_Number_In_Array_Java8Stream_Example2 {

	public static void main(String args[]) {

		List<Integer> numbers = Arrays.asList(12, 18, 15, 8, 31);
		
		int secondLargest = numbers.stream()
				                   .sorted(Comparator.reverseOrder())
				                   .limit(2)
							       .skip(1)
							       .findFirst()
							       .get();
		System.out.println("Second Largest Number in the Array is: "+secondLargest);
	}
}

 

Output:

Second Largest Number in the Array is: 18

find second largest number in an array using java 8 stream

In above example, It first sorts the array in descending order, then limits the stream to the first 2 elements using limit(2), then skip the first element using skip(1), and finally finds the first element in the remaining stream, which is the second largest number.

skip method java 8 stream

Java 8 – How to find the Second Largest Number in an Array? – Simplest Examples Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts