How is takeWhile different from a filter?

How does the takeWhile () method differ from filter () in Java 9. What additional utility does it have?

Stream.of(1,2,3,4,5,6,7,8,9,10).filter(i -> i < 4 )
        .forEach(System.out::println);

Perhaps this will be as follows:

Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i < 4 )
        .forEach(System.out::println);

What did this new feature need?

+4
source share
4 answers

filter will remove all elements from the stream that do not satisfy the condition.

takeWhile will interrupt the flow upon the first occurrence of an element that does not satisfy the condition.

eg.

Stream.of(1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1)
    .filter(i -> i < 4 )
    .forEach(System.out::print);

will print

123321

but

Stream.of(1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1)
    .takeWhile(i -> i < 4 )
    .forEach(System.out::print);

will print

123

+8
source

According to this blogpost: https://blog.codefx.org/java/java-9-stream/

, , , , . , , . , , .

, .

:

Stream.of("a", "b", "c", "", "e")
    .takeWhile(s -> !String.isEmpty(s));
    .forEach(System.out::print);

abc. , ( - 4- ). , .

+2

TakeWhile

, ,

,

Stream.of(1,2,3,4,5,6,7,8,9,10).filter(i -> i % 2 == 0 )
    .forEach(System.out::println);

TIO

2 10 .

Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i % 2 == 0 )
    .forEach(System.out::println);

TIO

, 1 , , -.

+2

It can be used to get the index of the first value null, for example.

Stream.of("Test", "Test2", null, "Test2", null).takeWhile(Objects:isNull).count();

You can do the same with filter, but in this case you will need a condition to break the filter as soon as you get the first null value. Therefore, in practice, filterit is not suitable for this kind of work, but takeWhilefor this particular case.

0
source

Source: https://habr.com/ru/post/1687883/


All Articles