Should we always check for Optional when using streams in Java8?

Viewed 180

The method get() always become marked in my intellij idea. Compiler says that i should use method isPresent as well. My colleagues say that i should not pay attention to that notice. Anyway, i decided to ask here.

    List<Integer> list  = new ArrayList<>();
    list.add(5);
    list.add(6);
    list.add(4);
    list.add(7);
    list.add(3);
    int result = list.stream().reduce((accumulator,element) ->
    accumulator*element).get(); // this get() is mentioned above
2 Answers

The result of your reduce is Optional. Optional.get method can throw error : documentation if value is not present. In your case it is present and seems like the warning can be ignored.

There could be case where you have your List as input parameter for the method. In those cases you would need to check if it is empty before running your reduce method or check if Optional has value via isPresent method to avoid this exception NoSuchElementException

First try to create an Optional and then get() it after checking isPresent.

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class Test {
    public static void main(String[] args) {
        List<Integer> list  = new ArrayList<>();
        list.add(5);
        list.add(6);
        list.add(4);
        list.add(7);
        list.add(3);
        int result = 0;
        Optional<Integer> optional = list.stream().reduce((accumulator, element) -> accumulator*element);
        if(optional.isPresent()) {
            result = optional.get();
        }
        System.out.println(result);
    }
}
Related