3

In my stream I want to get MainMenuOption based on user's input. If enum MainMenuOptions contains such option I want to return it, if not - print some message "THERE IS NO SUCH OPTION" and get user's input again.

return Arrays.stream(MainMenuOptions.values())
            .filter(x -> x.getCommand().equals(ConsoleInput.getNextLineFromUser()))
            .findFirst() // it returns Optional<MainMenuOptions>
            .orElse(); //or Else return some value, cannot do something

How I can achive it with Java Steams?

Thank you in advance.

3
  • 1
    A thought, return the Optional<MainMenuOptions> and leave to the caller to print any message. The caller may for example use ifPresentOrElse() (since Java 9). Commented Jun 17, 2020 at 18:37
  • You can throw custom exception and ask user to select again if it raise orElseThrow(()->new MenuOptionNotFoundException()) Commented Jun 17, 2020 at 18:44
  • These solutions are also good. Thank you. Commented Jun 17, 2020 at 19:19

1 Answer 1

5

Use a Optional.map operation before orElse to transform to Optional<String> such as

return Arrays.stream(MainMenuOptions.values())
        .filter(x -> x.getCommand().equals(ConsoleInput.getNextLineFromUser()))
        .findFirst()
        .map(MainMenuOptions::name)
        .orElse("THERE IS NO SUCH OPTION");
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.