Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java 8 Optional for List of String as output

I want to use Optional for a method which returns a List

Lets say the function is

public Output getListOfSomething() {
    // In some cases there is nothing to return and hence it makes sense to have return 
    // type as Optional here
}

Hence the function looks like :

public Optional<List<String>> getListOfSomething() {
    // return something only when there is some valid list
}

Now I want to do something if the list is present so something like :

Optional<List<String>> listOfSomething = getListOfSomething();

int size = 0;

listOfSomething.ifPresent(size = listOfSomething.get().size());

I am new to Optional and have gone through the articles about Optional and it seems like this should work however am getting syntax error in my IDE :

method ifPresent is not applicable for the arguments (void).

I wanted to get some help from developers who might be more fluent with lamdas in java 8.

like image 820
Scorpion Avatar asked May 07 '15 08:05

Scorpion


People also ask

How do you get a String out of Optional?

Java 8 – Convert Optional<String> to String In Java 8, we can use . map(Object::toString) to convert an Optional<String> to a String .

Why do we use Optional in Java 8 Give Explanation using a real life example?

Java 8 Optional ExampleOptional can minimize the number of null checks you do in your code by explicitly saying that value can be null and setting proper default values. If you're going to use null, consider the @Nullable annotation.


1 Answers

It's important to think about the Semantics here.

Your method could return a List, or "no list".

If it returns a List, it could return an Empty list.

You should ask, "is there a semantic reason to distinguish between an Empty List, and No List?" Sometimes there is a good design reason to make the difference, but it is rare. Think long and hard before deciding that Empty and Null are different in your case. Part of the reason to avoid No List, is that it reduces "special cases" that the client code has to consider. For example, if they have to do something for every item returned, but you could also return null, they have to do a special check for null before going into a for each loop. A for each does nothing if the list is empty.

If a "No List" is distinct from an "Empty List" in your problem domain, then it is sometimes useful to return wrapper class that helps client code distinguish between those conditions, and handle them appropriately. Optional is one such generic class, but your domain may call for something more specific (even if it mimics the functionality of Optional, it might have better semantic definition).

like image 62
Daniel Avatar answered Oct 03 '22 01:10

Daniel