FranzF
FranzF

Reputation: 123

How to move to the next value in a loop when using Java 8 Stream API

When using external iteration over an java collectios we use keyword "continue" for move to the next value in a loop. What about in the case, when we use java stream API? Example:

List<User> users;

for(Item item : item){
    users.stream()
        .filter(user -> user.getName().equals("Tom"))
        .findFirst()
        .ifPresent(move to the next value in a outer loop(items) ???? like **continue**;);

    more code here...
}

Without stream:

 for(Item item : item){
    for(User user : users){
     if(user.getName("Tom") exist = true;
    }
  if (exist) continue;

    more code here...
}

Upvotes: 3

Views: 767

Answers (3)

Nikolas
Nikolas

Reputation: 44398

The Stream-API doesn't provide the iteration mechanism like the Iterator does, for this you have to use the Iterator<User>. However, it's good to filter the correct values first.

List<User> filteredUsers = users.stream()
    .filter(user -> user.getName().equals("Tom"))
    .collect(Collectors.toList());

Now get an Iterator<User> and iterate through.

Iterator<User> iterator = filteredUsers.iterator();
while (iterator.hasNext()) {
    User user = iterator.next()
    // Take a control over the further iteration here...
}

Edit:

According to your edit, you want to find out if any User has a name Tom, then perform the iteration over the items. Use the anyMatch(Predicate<? super T> predicate) method which returns true if any element of the stream matches the predicate. It accepts the same predicate as the filter(Predicate<? super T> predicate) does.

if (users.stream().anyMatch(user -> user.getName().equals("Tom"))) {
    for (Item item : item) {
        // ...
    }
}

Edit2: As @Bohemian has correctly noted, consider checking the presence of the element with each iteration since there may be an element with "Tom" added and the condition no longer remains false.

Upvotes: 2

Bohemian
Bohemian

Reputation: 425033

Maybe you just want:

for (Item item : item){
    if (users.stream().anyMatch(u -> u.getName().equals("Tom"))) {
        continue;
    }

    // more code here...
}

Upvotes: 2

Pratik soni
Pratik soni

Reputation: 108

Java stream api is used only to work on that particular stream of elements. You can never use it for control statements like ‘break’ or ‘continue’ to control external loops (like here you want to control ‘Item’ loop).

Upvotes: 2

Related Questions