Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is takeWhile different from filter?

How is takeWhile() different from filter() in Java 9. What extra utility does it have?

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

This is perhaps what following would do

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

What was the need of this new function then?

like image 681
Rajeev Ranjan Avatar asked Oct 20 '17 13:10

Rajeev Ranjan


2 Answers

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

takeWhile will abort the stream on the first occurrence of an item which does not satisfy the condition.

e.g.

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

like image 64
OldCurmudgeon Avatar answered Oct 04 '22 04:10

OldCurmudgeon


The difference

takeWhile

Takes values while the filter is true, then stops

filter

Takes all the values that match the filter

Example

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

TIO

This outputs all of the even numbers from 2 to 10 inclusive.

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

TIO

This outputs nothing, as 1 is not even, so it stops before outputing anything.

like image 25
jrtapsell Avatar answered Oct 04 '22 06:10

jrtapsell