In  this tutorial, we will see “How to find the maximum and minimum of two numbers without using if-else but in fact with the help of streams in Java 8?”

find max and min of two numbers using Java 8 Streams

Java 8 – How to find the max and min of two numbers without using if-else statements? Share on X

/**
 * Find the find the maximum and minimum of two numbers in array without using if-else statements in Java 8 
 * @author Deepak Verma
 *
 */

import java.util.stream.IntStream;

public class Find_max_min_of_two_number_without_using_ifelse_in_Array_using_Java8 {

	public static void main(String[] args) {

		int x = 80;
        int y = 900;
        int[] arrayOfNumbers = {x, y};
        
        // Finding the minimum of two numbers
        int minNumber = IntStream.of(arrayOfNumbers).min().getAsInt();
        System.out.println("Minimum: " + minNumber);
        
        // Finding the maximum of two numbers
        int maxNumber = IntStream.of(arrayOfNumbers).max().getAsInt();
        System.out.println("Maximum: " + maxNumber);
        
	}

}

 

Output:

Minimum: 80
Maximum: 900

find max and min of two numbers using Java 8 Streams

In the above example, It uses Java 8’s IntStream class to convert an array of integers into a stream, and then finds the minimum and maximum values using the min() and max() methods, respectively.

Java 8 – How to find the max and min of two numbers without using if-else statements? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts