Write a Java program using Lambda Expression to find the maximum values in a list of integers


The java program that finds the maximum number from a list of integers using Java Streams and the reduce operation. Here's an explanation of the code:

  • import java.util.Arrays;: This line imports the Arrays class from the java.util package, which is used to create a list of integers from an array.
  • import java.util.List;: This line imports the List class from the java.util package, which is used to work with lists.
  • import java.util.Optional;: This line imports the Optional class, which is used to represent optional values that can be absent.
  • The MaximumNumber class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<Integer> num = Arrays.asList(13, 21, 78, 23, 35, 8, 1);: This line creates a list of integers named num containing the values 13, 21, 78, 23, 35, 8, and 1.
    • Optional<Integer> maxNum = num.stream().reduce((a, b) -> a > b ? a : b);: This line uses a stream to reduce the list of numbers to the maximum value using the reduce operation. The lambda expression (a, b) -> a > b ? a : b compares two values a and b and returns the greater value as the result. The reduce operation returns an Optional containing the maximum value.
    • The if block checks if the maxNum contains a value using the isPresent() method of the Optional. If the value is present, it prints "Maximum Number" followed by the maximum number using the get() method. If the value is not present (e.g., when the list is empty), it prints "Numbers Not Found."

Source Code

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
 
public class MaximumNumber
{
	public static void main(String[] args)
	{
		List<Integer> num = Arrays.asList(13, 21, 78, 23, 35, 8, 1);
 
		Optional<Integer> maxNum = num.stream().reduce((a, b) -> a > b ? a : b);
 
		if (maxNum.isPresent())
		{
			System.out.println("Maximum Number : " + maxNum.get());
		}
		else
		{
			System.out.println("Numbers Not Found");
		}
	}
}

Output

Maximum Number : 78

Example Programs