Вопрос

Why does the .next() return 7 and not 8 as I would have expected?

List<Integer> intList = new ArrayList<>();

IntStream.range(0, 10)
    .forEach(i -> intList.add(i));

int value = intList.stream()
            .filter(number -> number == 7)
            .iterator()
            .next();         // returns 7, not 8.
Это было полезно?

Решение

The filter is filtering the stream down to only elements that match the condition number == 7 (i.e. only a single element, which happens to be the Integer 7), then next() returns the first (and only) element. Remember, in order to get the first element from an Iterator, you need to call next() once.

If you definitely want the first element after the 7 in this ordered list, you can change your filter to number -> number > 7.

Другие советы

Aside from the issue with the wrong filter predicate pointed out by other answers, using iterator() should be your last resort. This method (and its friend, spliterator()) are consisted "escape hatches" for the case where the standard stream methods can't do what you need.

In this case, if you only want the first element, you can call findFirst(). If you want to put the results into an array or collection, use toArray() or collect().

This is actually correct because you are filtering your list and only considering elements that satisfy the lambda expression number -> number == 7. So only one of the elements in your list gets through.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top