Java 8 find maximum number using stream is example specified here.

Example 1: stream + reduce method

package com.javadeveloperzone;

import java.util.Arrays;

/**
 * Created by JavaDeveloperZone on 30-04-2017.
 */
public class MaxNumberUsingStreamWay1 {
    public static void main(String... args) {
        java.util.List<Integer> integer = Arrays.asList(1, 2, 15, 10, 5, 5, 10, 3, 4);
        int maxNumber = integer.stream().reduce(0, (max, i) -> {
            max = max < i ? i : max;
            return max;
        });
        System.out.print("Maximum number is" + maxNumber);
    }
}

 

Example 2: stream + max method

package com.javadeveloperzone;

import java.util.Arrays;
import java.util.Optional;

/**
 * Created by JavaDeveloperZone on 30-04-2017.
 */
public class MaxNumberUsingStreamWay2 {
    public static void main(String... args) {
        java.util.List<Integer> integer = Arrays.asList(1, 2, 15, 10, 5, 5, 10, 3, 4);
        Optional<Integer> maxNumber = integer.stream().max((number1, number2) -> {
            if (number1 == number2) {
                return 0;
            } else if (number1 > number2) {
                return 1;
            } else
                return -1;
        });
        System.out.print("Maximum number is" + maxNumber.get());
    }
}

 

References:

https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *