In this article, we will discuss how to find second largest number in an Arrays and List using Java 8 Stream
Read Java – Find Second Largest number in an Arrays or List ? for finding second largest number without using Java 8 syntax
1. Finding Second Largest number in an Arrays :
We will follow below 2 approaches to get 2nd Largest number in an Arrays
- Using Stream.skip() method
- Using Stream.limit() & Stream.skip() methods
1.1 Using Stream.skip() method :
- First, get Stream from Arrays using Arrays.stream() method
- Convert primitive integers into Integer objects using Stream.boxed() method
- Sort Integer objects in descending-order using Comparator.reverseOrder() inside Stream.sorted() method
- As integer Arrays sorted in descending-order, 2nd element in the Arrays will be the second largest number
- We will skip first number which is the largest number using Stream.skip() method
- Stream.findFirst() method will return 2nd largest number in the Arrays
- Finally, we will print 2nd largest number to the console
FindSecondLargestNumberInAnArraysUsingJava8Stream.java
package in.bench.resources.second.largest.number;
import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
public class FindSecondLargestNumberInAnArraysUsingJava8Stream {
public static void main(String[] args) {
// random numbers
int[] numbers = {5, 9, 11, 2, 8, 21, 1};
// print to console
System.out.println("Numbers in an Arrays : "
+ Arrays.toString(numbers));
// Execution - start time
LocalTime startTime = LocalTime.now();
// sort in descending-order and get 2nd largest element
int secondLargestNumber = Arrays
.stream(numbers)
.boxed()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.get();
// Execution - end time
LocalTime endTime = LocalTime.now();
// find difference
Duration duration = Duration.between(startTime, endTime);
long differenceInNano = duration.getNano();
// print sum to console
System.out.println("\nSecond largest number in an Arrays is - "
+ secondLargestNumber);
// print execution time in Nano seconds
System.out.println("\nExecution time - "
+ differenceInNano + " ns");
}
}
Output:
Numbers in an Arrays : [5, 9, 11, 2, 8, 21, 1]
Second largest number in an Arrays is - 11
Execution time - 15000000 ns
1.2 Using Stream.limit() & Stream.skip() methods :
- This example is very similar to above example 1.1 except that we are limiting top 2 numbers after sorting using Stream.limit() method which are the largest & 2nd largest numbers in the Arrays
- Using Stream.skip() method, we are skipping 1st element and remaining one element in the Arrays is the 2nd largest number
FindSecondLargestNumberInAnArraysUsingJava8Stream.java
package in.bench.resources.second.largest.number;
import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
public class FindSecondLargestNumberInAnArraysUsingJava8Stream {
public static void main(String[] args) {
// random numbers
int[] numbers = {5, 9, 11, 2, 8, 21, 1};
// print to console
System.out.println("Numbers in an Arrays : "
+ Arrays.toString(numbers));
// Execution - start time
LocalTime startTime = LocalTime.now();
// sort in descending-order and get 2nd largest element
int secondLargestNumber = Arrays
.stream(numbers)
.boxed()
.sorted(Comparator.reverseOrder())
.limit(2)
.skip(1)
.findFirst()
.get();
// Execution - end time
LocalTime endTime = LocalTime.now();
// find difference
Duration duration = Duration.between(startTime, endTime);
long differenceInNano = duration.getNano();
// print sum to console
System.out.println("\nSecond largest number in an Arrays is - "
+ secondLargestNumber);
// print execution time in Nano seconds
System.out.println("\nExecution time - "
+ differenceInNano + " ns");
}
}
Output :
Numbers in an Arrays : [5, 9, 11, 2, 8, 21, 1]
Second largest number in an Arrays is - 11
Execution time - 31000000 ns
2. Finding Second Largest number in List or ArrayList :
We will follow below 2 approaches to get 2nd Largest number in List or ArrayList
- Using Stream.skip() method
- Using Stream.limit() & Stream.skip() methods
2.1 Using Stream.skip() method :
- First, get Stream from List using List.stream() method
- Sort Integer objects in descending-order using Comparator.reverseOrder() inside Stream.sorted() method
- As integer List is sorted in descending-order, 2nd element in the List or ArrayList will be the second largest number
- We will skip first number which is the largest number using Stream.skip() method
- Stream.findFirst() method will return 2nd largest number in the List
- Finally, we will print 2nd largest number to the console
FindSecondLargestNumberInListUsingJava8Stream.java
package in.bench.resources.second.largest.number;
import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FindSecondLargestNumberInListUsingJava8Stream {
public static void main(String[] args) {
// random numbers
List<Integer> numbers = Arrays.asList(5, 9, 11, 2, 8, 21, 1);
// print to console
System.out.println("Original Integer List : " + numbers);
// Execution - start time
LocalTime startTime = LocalTime.now();
// sort in descending-order and get 2nd largest element
int secondLargestNumber = numbers
.stream()
.sorted(Comparator.reverseOrder())
.skip(1)
.findFirst()
.get();
// Execution - end time
LocalTime endTime = LocalTime.now();
// find difference
Duration duration = Duration.between(startTime, endTime);
long differenceInNano = duration.getNano();
// print sum to console
System.out.println("\nSecond largest number in List is - "
+ secondLargestNumber);
// print execution time in Nano seconds
System.out.println("\nExecution time - "
+ differenceInNano + " ns");
}
}
Output :
Original Integer List : [5, 9, 11, 2, 8, 21, 1]
Second largest number in List is - 11
Execution time - 16000000 ns
2.2 Using Stream.limit() & Stream.skip() methods :
- This example is very similar to above example 2.1 except that we are limiting top 2 numbers after sorting using Stream.limit() method which are the largest & 2nd largest numbers in the List or ArrayList
- Using Stream.skip() method, we are skipping 1st element and remaining one element in the List is the 2nd largest number
FindSecondLargestNumberInListUsingJava8Stream.java
package in.bench.resources.second.largest.number;
import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FindSecondLargestNumberInListUsingJava8Stream {
public static void main(String[] args) {
// random numbers
List<Integer> numbers = Arrays.asList(5, 9, 11, 2, 8, 21, 1);
// print to console
System.out.println("Original Integer List : " + numbers);
// Execution - start time
LocalTime startTime = LocalTime.now();
// sort in descending-order and get 2nd largest element
int secondLargestNumber = numbers
.stream()
.sorted(Comparator.reverseOrder())
.limit(2)
.skip(1)
.findFirst()
.get();
// Execution - end time
LocalTime endTime = LocalTime.now();
// find difference
Duration duration = Duration.between(startTime, endTime);
long differenceInNano = duration.getNano();
// print sum to console
System.out.println("\nSecond largest number in List is - "
+ secondLargestNumber);
// print execution time in Nano seconds
System.out.println("\nExecution time - "
+ differenceInNano + " ns");
}
}
Output:
Original Integer List : [5, 9, 11, 2, 8, 21, 1]
Second largest number in List is - 11
Execution time - 16000000 ns
3. Find 2nd Largest number from Arrays/List containing duplicates :
In the below illustration, we will find 2nd largest number from ArrayList or Arrays containing duplicates
- Below list contains 7 integers where number 5 & 9 is repeated twice
- Note: 9 is the largest number & 8 is the 2nd largest number
FindSecondLargestNumber.java
package in.bench.resources.second.largest.number;
import java.time.Duration;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class FindSecondLargestNumber {
public static void main(String[] args) {
// random numbers
List<Integer> numbers = Arrays.asList(5, 9, 5, 2, 8, 9, 1);
// print to console
System.out.println("Original Integer List : " + numbers);
// Execution - start time
LocalTime startTime = LocalTime.now();
// sort in descending-order and get 2nd largest element
int secondLargestNumber = numbers
.stream()
.distinct()
.sorted(Comparator.reverseOrder())
.limit(2)
.skip(1)
.findFirst()
.get();
// Execution - end time
LocalTime endTime = LocalTime.now();
// find difference
Duration duration = Duration.between(startTime, endTime);
long differenceInNano = duration.getNano();
// print sum to console
System.out.println("\nSecond largest number in List is - "
+ secondLargestNumber);
// print execution time in Nano seconds
System.out.println("\nExecution time - "
+ differenceInNano + " ns");
}
}
Output :
Original Integer List : [5, 9, 5, 2, 8, 9, 1]
Second largest number in List is - 8
Execution time - 16023800 ns
4. Points to remember w.r.t execution time:
- Execution time differs in different platforms
- With small set of numbers, we may not find large difference in execution time
- But with large set of numbers, difference will be significant to consider
Related Articles:
- Java 8 – Find Largest number in an Arrays or List or Stream ?
- Java 8 – Find Smallest number in an Arrays or List or Stream ?
- Java 8 – Find 2nd Largest number in an Arrays or List or Stream ?
- Java 8 – Find 2nd Smallest number in an Arrays or List or Stream ?
- Java 8 – Find sum of Largest 2 numbers in an Arrays or List or Stream ?
- Java 8 – Find sum of Smallest 2 numbers in an Arrays or List or Stream ?
- Java 8 – Find 1st and Last elements in an Arrays ?
- Java 8 – Find 1st and Last elements in a List or ArrayList ?
- Java 8 – Find 1st and Last elements in a Set or HashSet ?
- Java 8 – Find 1st and Last entries in a Map or HashMap ?
- Java 8 – Find sum and average of a List or ArrayList ?
- Java 8 – How to calculate sum and average of an Arrays ?
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#skip-long-
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#limit-long-
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
- https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-int:A-
Happy Coding !!
Happy Learning !!