Printing max element in a Deque<Integer>

1.2k views Asked by At

I have a Deque from Integers, which I'm using as a Que. I have to add and remove elements from it and in some cases I need to print the max value in the Que.

The thing that I've tried is:

System.out.println(deque.stream().max(Integer::compareTo));

But it prints - Optional[the current max int].

Thank you!

5

There are 5 answers

2
Alex Bondor On BEST ANSWER

That is because the max method of java.util.Stream returns your value wrapped in Optional. This is the signature of the max method Optional<T> max(Comparator<? super T> comparator);

The example below would provide you the expected behaviour:

Optional<Integer> optionalOfMax = deque.stream().max(Integer::compareTo);
System.out.println(optionalOfMax.orElseThrow());
1
deHaar On

You can just use the code you have written and extend it by .get().

The following code

public static void main(String[] args) {
    // create a Deque that holds Integers
    Deque<Integer> myDQ = new ArrayDeque<Integer>();
    // add some of them
    myDQ.add(12);
    myDQ.add(13);
    myDQ.add(14);
    myDQ.add(15);
    myDQ.add(16);
    myDQ.add(20);
    myDQ.add(17);
    myDQ.add(18);
    myDQ.add(19);
    // and print
    System.out.println(
            myDQ.stream()
                .max(Integer::compareTo) // the largest one
                .get() // not as Optional but only as Integer
    );
}

just prints 20.

0
Arvind Kumar Avinash On

You can do it as follows:

deque.stream().max(Integer::compareTo).ifPresent(System.out::println);

Note that deque.stream().max(Integer::compareTo) returns Optional<Integer>.

Alternatively,

deque.stream().flatMapToInt(x -> IntStream.of(x)).max().ifPresent(System.out::println);

Stream#flatMapToInt returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

0
k314159 On

You can unbox the Integer wrappers in your queue and use IntStream.max(), which returns an OptionalInt:

deque.stream().mapToInt(Integer::intValue)
    .max()
    .ifPresent(System.out::println);

This will do nothing if max() returns OptionalInt.empty(), which happens when the deque is empty. If you want to check for emptiness, you can do, for example:

deque.stream().mapToInt(Integer::intValue)
    .max()
    .ifPresentOrElse(System.out::println,
            () -> throw new RuntimeException("Attempt to get max of empty collection"));
0
Benjamin Schüller On

The max-Method returns an java.util.Optional. If you just want to return a int-Value you can use the orElse-Method from java.util.Optional to return the given value or, if not present, another default.

System.out.println(deque.stream().max(Integer::compareTo).orElse(0));