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

Introduction

Finding the second largest number in a list of integers can be easily accomplished using Java 8 features like Stream and Collectors. This guide will walk you through writing a Java 8 program to find the second largest number in a list of integers.

Problem Statement

Create a Java program that:

  • Accepts a list of integers.
  • Identifies and returns the second largest number.

Example:

  • Input: [10, 20, 35, 50, 50, 75, 65]

  • Output: 65

  • Input: [5, 8, 12, 7, 3]

  • Output: 8

Solution Steps

  1. Read the List of Integers: Provide a list of integers either by user input or as part of a method.
  2. Filter Unique Numbers: Use distinct() to remove duplicate numbers.
  3. Sort the List in Descending Order: Use sorted() in reverse order to sort the numbers.
  4. Find the Second Largest Number: Skip the largest element and retrieve the second one.
  5. Display the Result: Print the second largest number.

Java 8 Program

// Java 8 Program to Find the Second Largest Number in the List of Integers
// Author: https://www.rameshfadatare.com/

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) {
        List<Integer> numbers = Arrays.asList(10, 20, 35, 50, 50, 75, 65);

        // Step 1: Find the second largest number in the list
        Optional<Integer> secondLargest = numbers.stream()
                .distinct() // Step 2: Remove duplicates
                .sorted(Comparator.reverseOrder()) // Step 3: Sort in descending order
                .skip(1) // Step 4: Skip the first (largest) number
                .findFirst(); // Step 5: Get the second largest number

        // Step 6: Display the result
        if (secondLargest.isPresent()) {
            System.out.println("The second largest number is: " + secondLargest.get());
        } else {
            System.out.println("The list does not have enough unique numbers.");
        }
    }
}

Explanation

Step 1: Initialize the List of Integers

  • The list numbers contains a series of integers that may include duplicates.

Step 2: Remove Duplicates

  • The distinct() method is used to remove any duplicate numbers from the list.

Step 3: Sort the List in Descending Order

  • The sorted(Comparator.reverseOrder()) method sorts the list in descending order so that the largest number appears first.

Step 4: Skip the Largest Element

  • The skip(1) method skips the first element (the largest) and moves to the second element.

Step 5: Retrieve the Second Largest Number

  • The findFirst() method retrieves the first element after skipping, which will be the second largest number.

Step 6: Display the Result

  • If the list contains enough unique numbers, the second largest number is printed. Otherwise, a message is shown indicating that there are not enough numbers to determine a second largest value.

Output Example

The second largest number is: 65

Example with Different Input

If you modify the input list to:

List<Integer> numbers = Arrays.asList(5, 8, 12, 7, 3);

The output will be:

The second largest number is: 8

Conclusion

This Java 8 program demonstrates how to find the second largest number in a list of integers using Stream, distinct(), sorted(), and skip() methods. By leveraging functional programming features, the code is concise and easy to understand. This exercise is valuable for learning how to manipulate streams and solve list-related problems using Java 8 in an efficient manner.

Comments