🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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:
65Input:
[5, 8, 12, 7, 3]Output:
8
Solution Steps
- Read the List of Integers: Provide a list of integers either by user input or as part of a method.
- Filter Unique Numbers: Use
distinct()to remove duplicate numbers. - Sort the List in Descending Order: Use
sorted()in reverse order to sort the numbers. - Find the Second Largest Number: Skip the largest element and retrieve the second one.
- 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
numberscontains 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment