3

I would like to have opportunity to make null check inside the stream:

firstItem = array.stream().min(myComparator).get();
if(firstItem!=null){
     name = firstItem.getData().get("Name")
}

Is it possible to get name right from the Stream?

0

3 Answers 3

2

Note that Optional can't contain null values, so your code will either execute the conditional, or fail with an exception at get().

You could change the get() to orElse(null); but you'd still need the separate conditional.

Instead, use Optional.map, then orElse:

String name = 
    array.stream()
        .min(myComparator)
        .map(m -> m.getData().get("name"))
        .orElse(someDefaultValue);

Of course, if you don't want to assign a default value, you can omit the final orElse, and make the variable type Optional<String>.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

String name = array.stream().min(myComparator) //
.map(item -> item.getData().get("Name")) //
.orElse("No Name");

2 Comments

You'd need to use orElse(null) instead of get(); but why unwrap and then immediately re-wrap the optional?
My bad, went with OP code and tried to wrap it in Optional, corrected now
0

Unfortunetly there is no way to avoid either some kind of check or a default value (as was already posted in previous answers). Having said that, there is a nice way of doing checks with optionals. Let me give you an example. I've created simple class for tests.

 class ExampleData
    {
        private String name;
        private int value;

        public ExampleData(String name, int value) {
            this.name = name;
            this.value = value;
        }

        public String getName() {
            return name;
        }

        public int getValue() {
            return value;
        }

        @Override
        public String toString() {
            return "ExampleData{" +
                    "name='" + name + '\'' +
                    ", value=" + value +
                    '}';
        }
    }

Now lets write a simple test method.

 public void testApp()
    {
        ArrayList<ExampleData> array = new ArrayList<>(Arrays.asList(
                new ExampleData("TestName", 1),new ExampleData("TestName1", 2)));
        Optional<ExampleData> min = array
                .stream()
                .min(Comparator.comparingInt(ExampleData::getValue));

               min.ifPresent(System.out::println);



    }

Notice that i didn't use get() right away. Instead i used ifPresent method when i wanted to extract value. I don't know if you ever used C# language but this approach remind me of ? operator from c#.

In c# you would simply do something like this

String name = possibllyNullValue?.getName();

so here in Java you can do something similar with ifPresent()

Of course ifPresent returns void so it can be inconvenient in some cases.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.