JavaChallenge44

Govinda Raj
wolfie/JavaChallenge
2 min readApr 18, 2022

--

Please try to solve the challenge by yourself without any help from the compiler!

Hint: Java9 Stream API, takeWhile(), dropWhile(), break;

This challenge is made to check your Java 9 Stream API skills. For those who do not know, let’s understand the takeWhile() and the dropWhile() API of Stream. So both API has one common functionality which is break; statement.

takeWhile(Predicate) -> take all elements till predicate returns false.

dropWhile(Predicate) -> drop all elements till predicate returns false and take remaining elements.

Let’s execute the logic for numberList , takeWhile() will return {9,7} then dropWhile() will be executed and will return {7} . So the first stream contains {7} .

Now, let’s execute numberSet , takeWhile() will return {9,6,5,7,8} . There is a trick here, As we know set does not follow the order, so dropWhile() can return a different result every time we execute. Depending on the order of the input set, it will drop elements. So for now consider the same order for input set which is {9,6,5,7,8} so the dropWhile() will return {6,5,7,8} .

I hope, you understand the takeWhile() and dropWhile() API now.

Please follow the publication for more such challenges.

Note- Both APIs are short-circuiting stateful intermediate operations. You can read more about it here.

Want to read more about the stream API, here you can go — https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Image — For Marketing Purpose.

--

--

Govinda Raj
wolfie/JavaChallenge

Senior Software Developer. Tech Enthusiast and love coding. My portfolio: https://govinda-raj.github.io/