Foojay Today

Optional takeWhile dropWhile Java Challenge

May 10, 2021

The Optional concept is present in many programming languages. The main goal of the Optional class is to avoid NullPointerException. It’s much easier to deal with null values when we use the concepts of an Optional.

In this challenge, we will also explore the takeWhile and dropWhile methods from Java 9. Therefore you will be upgrading your knowledge with Optional, takeWhile, and dropWhile!

Are you prepared to have fun with this Java Challenge and refine your Java skills?

Take 5 minutes of your time and get this challenge done!

Optional TakeDropWhile ChallengeOptional TakeDropWhile Challenge

What will happen in the following code?

import java.util.List;
import java.util.Optional;

public class OptionalChallenge4 {

    public static void main(String... doYourBest) {
        List<Integer> list = List.of(10, 1, 3, 5, 7, 9);

        Optional<Integer> number =
                .takeWhile(i -> i > 5)
                .dropWhile(i -> i > 9)
                .or(() -> Optional.of(777));



A) Optional[777]
B) Optional[5]
C) Optional[10]
D) Optional[7]

Explanation (Spoiler Alert!):

In the takeWhile method, element 10 will be taken and then the looping will stop because the number 1 doesn't match the condition. Then, in the next line, elements will be dropped, and since 10 is greater than 9, it will be dropped. As in the end there are no results, the or statement will be executed, returning... what do you think? 🙂

If you want to try out this Java Challenge with an interactive quiz or watch the video explanation, you can access the following link:

Right on Challenger, keep rocking with Java! See you in the next challenge!



  • Rafael del Nero

    Java Champion, a passionate and creative developer who possesses strong technical knowledge and delivers solid systems focused on Spring and Java EE specifications for cloud applications. More than 10 years' ... Learn more

Comments (0)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Subscribe to foojay updates:
Copied to the clipboard