1

I am using Spring Data Mongo Pageable and Sonar giving me below error:

Optional<Order> optional = pageable.getSort().stream().findFirst();
if(optional.isPresent()) {
    direction = pageable.getSort().stream().findFirst().get().getDirection();
    property = pageable.getSort().stream().findFirst().get().getProperty();
}

SortOperation sortOperation = Aggregation.sort(direction, property); 

Error:

Call "Optional#isPresent()" before accessing the value.

I tried few options but nothing is working out.

halfer
  • 19,824
  • 17
  • 99
  • 186
PAA
  • 1
  • 46
  • 174
  • 282

1 Answers1

4

When you call pageable.getSort().stream() again inside your if statement you are creating a new Optional that you need to call .isPresent() on.

You should reuse the Optional you already have instead of creating the stream over and over, like this:

Optional<Order> optional = pageable.getSort().stream().findFirst();
if(optional.isPresent()) {
    direction = optional.get().getDirection();
    property = optional.get().getProperty();
}
Mark B
  • 183,023
  • 24
  • 297
  • 295
  • Thanks ! But this way I am really struggling to write mockito for the same. Question posted here: https://stackoverflow.com/questions/56135373/optional-cannot-be-returned-by-stream-in-mockito-test-classes – PAA May 14 '19 at 19:22