Java 8 Program to Find the Second Largest Number in the List of Integers

1. Introduction

Finding the second largest number in a list of integers is a common problem that tests a programmer's ability to manipulate collections and understand sorting mechanisms. In this blog post, we will tackle this problem using Java 8's Stream API, demonstrating an efficient and concise way to find the second largest number in a list.

2. Program Steps

1. Create a list of integers

2. Remove duplicates to ensure uniqueness of numbers

3. Sort the stream in descending order

4. Skip the largest number

5. Find the second-largest number

6. Display the second-largest number

3. Code Program

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

public class SecondLargestNumber {
    public static void main(String[] args) {
        // Creating a list of integers
        List<Integer> numbers = Arrays.asList(1, 3, 4, 5, 6, 6, 7, 2);

        // Finding the second largest number using Stream API
        Optional<Integer> secondLargest = numbers.stream()
                .distinct() // Remove duplicates
                .sorted(Comparator.reverseOrder()) // Sort the stream in descending order
                .skip(1) // Skip the largest number
                .findFirst(); // Find the second largest number

        // Displaying the second largest number
        secondLargest.ifPresent(number -> System.out.println("Second Largest Number: " + number));
    }
}

Output:

Second Largest Number: 6

Explanation:

This Java program finds the second largest unique number in a list by first removing duplicates and then sorting the remaining numbers in descending order. After skipping the first element (the largest number), it retrieves the next element, which is the second largest. This number is then printed to the console. If the list doesn't have at least two unique numbers, it won't print anything.

Comments