-2

I have method that return Optional of Book object (do not mind with names as it is just a sample of code). I want to fetch the size of list which is inside Book class:

public class Book {
    Integer b;

    DateTime dateOfCreation;

    Integer a;

    List<Integer> bookList;
}

So it goes like this:

public class Main {
    public static void main(String[] args) {

        Optional<Book> book = getBookObject();
        int sizeOfList = book.get().bookList.size();
    }

    static Optional<Book> getBookObject() {
        return Optional.of(new Book());
    }
}

I have warning within the get() which goes like Optional.get() without .ifPresent what is the proper approach to fetch this size of the list?

mara122
  • 313
  • 3
  • 10

2 Answers2

0

You have two options to avoid using Optional.get() directly as using it directly might throw NoSuchElementException:

book.ifPresent(b -> {
   int  sizeOfList = b.bookList.size();
   // do stuff with sizeOfList
});

The above code uses a Consumer callback to get the unwrapped Book object and use it.

The second one is to use, Optional.isPresent() which returns true if some value is present else it will return false:

int sizeOfList = book.isPresent() ? book.get().bookList.size() : 0;

We could also use Optional.orElse(otherValue) the otherValue is returned if the Optional is empty:

int sizeOfList = book.orElse(new Book()).bookList.size();

As per @Holger we could use Optional.map() to map it to the Optional<Integer> and return 0 with orElse() if the Optional was empty:

int sizeOfList = book.map(b -> b.bookList.size()).orElse(0);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
-1

To obtain an optional containing the size or an empty optional if the book is not present:

Optional<Integer> sizeOfListOptional = book.map((Book presentBook) -> presentBook.bookList.size());
Smutje
  • 17,733
  • 4
  • 24
  • 41
  • it's a duplicate, and it should be closed as one (I downvoted) – Andrew Tobilko Aug 20 '19 at 11:44
  • So is there a reason you don't close it and instead lecture other posters? – Smutje Aug 20 '19 at 11:45
  • i haven't found any proper answer for my question,that's why I asked the question. – mara122 Aug 20 '19 at 11:45
  • @Smutje but it is necessary to store it size as an Optiomal? Cannot have primitive tpye? – mara122 Aug 20 '19 at 11:50
  • The warning says it all: As you have an optional it is not safe that the value is present and you need to be able to treat both cases - that's why mapping into an optional is safe and accessing the value otherwise is not. – Smutje Aug 20 '19 at 11:55