Home > other >  How to get the number of elements from "Option<entity>"
How to get the number of elements from "Option<entity>"

Time:09-22

When we get the number of elements in List use .size() but if we get the number of elements in Optional how to get...

In List:

List<User> data = this.Service.getUserById(id);
System.out.print(data.size());

In Optional:

Optional<User> data = this.Service.getUserById(id);
System.out.print(); // how to get in Optional

CodePudding user response:

An Optional<User> is not a list, what you are getting back is MAYBE a single user, or not, and it is your job to check if it returned a SINGLE user or not. The optional contains a User not a List<User>

If you want to get the user if it was returned, there are several ways.

This is one way, to get the user, but as mentioned there are several ways.

// This line returns maybe a single user, not a list of users.
Optional<User> data = this.Service.getUserById(id);
if(data.isPresent()) {
    final User user = data.get(); 
}

You can read more about using optionals here:

Java Optionals

CodePudding user response:

In this case there must 0 or 1 result. if you have more than 1 user references to the same id, you have to use List<User> users as result. But more than 1 user references to 1 id may be issue for you in the future. Example for Optinal case:

this.serviceName.findById(id).ifPresent(System.out::println);
  • Related