continue doesn't work when using streams and the map

dernor00 :

I have this simple code where I use a stream and a .map() function. I do a null check for the id, and inside it a add a continue The continue gives me an error: Continue outside of loop When I remove the continue I don't get an error, but I don't know if the behaviour is the same?

public List<Long> getIds(final Long[][] value){
     List<Long> list = Arrays.stream(value).map(result ->{
                final Long id = result[1];
                if(id == null){
                    continue; // This part doesn't work (error: Continue outside of loop)
                }
                return id;
            }).collect(Collectors.toList());
}

Any suggestion on why this happens with .streams? Whereas, when I don't use the stream I can use continue.

The question has been marked as duplicate, but it's not the case. Using return surely works in forEach, where no return type is requested, but not in map.

Andronicus :

continue works in a for loop. You can use flatMap as a workaround:

 List<Long> list = Arrays.stream(value).flatMap(result ->{
            final Long id = result[1];
            return Stream.ofNullable(id);
        }).collect(Collectors.toList());

You can also make it more concise by using Stream.ofNullable directly as @Naman suggests:

 List<Long> list = Arrays.stream(value)
    .flatMap(result -> Stream.ofNullable(result[1]))
    .collect(Collectors.toList());

The other, more elegant version of my firstly proposed method by @Holger would be to use the predicate in the filter:

 List<Long> list = Arrays.stream(value)
    .map(result -> result[1])
    .filter(Objects::nonNull)
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=11922&siteId=1