Java Program: Find Second Smallest and Largest Elements in a List of Integers using Streams
Write a Java program to find the second smallest and largest elements in a list of integers using streams.
Sample Solution:
Java Code:
Sample Output:
List of numbers: [1, 17, 54, 14, 14, 33, 45, -11] Second smallest element: 1 Second largest element: 45
Explanation:
In the above exercise,
We create a list of integers (numbers) and use streams to find the second smallest element by applying distinct, sorting the elements in ascending order, skipping the first element, and locating the first element. Similarly, we find the second largest element by sorting the elements in descending order. The orElse method handles the case when the list is empty or there are no second smallest/largest elements.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Java program to find the second smallest and second largest values in a list of integers using streams after sorting.
- Write a Java program to extract the second smallest and second largest numbers from a list by first removing duplicates using streams.
- Write a Java program to compute the second smallest and second largest numbers by mapping a list to a sorted stream and then using skip().
- Write a Java program to find the second smallest and second largest elements in a list using streams and then calculate their sum.
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Find Maximum and Minimum Values in a List of Integers using Streams.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics