0

I have a for loop which iterates across the employeeId list. In each iteration it calls a service to see if it has any values, if we get any values for an id then we need to skip all the remaining iteration. I have done that by using traditional for loop like as shopn below

for(int i=0; i<employeeIdLists.length; i++) {
    userDetails = someService.getUserId(employeeIdLists.get(i));
    if(userDetails != null) {
        i = employeeIdLists.length; // skip rest of the iteration
    }
}

I would like to know if I can do the similar one using Java Streams. I tried some but this is not meeting the expectations

employeeIdLists.stream()
.map(id -> someService.getUserId(id))
.filter(userDetails -> userDetails!=null)
.collect(Collectors.toList());
Naman
  • 27,789
  • 26
  • 218
  • 353
Alex Man
  • 4,746
  • 17
  • 93
  • 178
  • since you are actually looking for the first occurrence or any such occurrence you shall be aware of `findAny` and `findFirst` – Naman Dec 03 '20 at 15:11

1 Answers1

1

Yes, you do that with findAny() or findFirst(), which would stop the pipeline the first time a value is found (after the filter, in your case):

userDetails = employeeIdLists.streams()
    .map(id -> someService.getUserId(id))
    .filter(userDetails -> userDetails!=null)
    .findAny()
    .orElse(null); //null if all values were null

In this pipeline, userDetails will be set to a value that did not get a null result from the service, and the pipeline will be stopped as soon as such value is found.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
  • Thanks for the answer, which one suits for my case `findAny()` or `findFirst()` – Alex Man Dec 03 '20 at 15:16
  • If you want to deterministically get the first element that got a non-null result, then use `findFirst()`. Otherwise `findAny()` should be fine. – ernest_k Dec 03 '20 at 15:21