Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8071670

java.util.Optional: please add a way to specify if-else behavior

    Details

    • Subcomponent:
    • Resolved In Build:
      b52
    • CPU:
      generic
    • OS:
      generic

      Backports

        Description

        A DESCRIPTION OF THE REQUEST :
        I would like a way to easily specify if-else behavior with an Optional.

        Proposal 1:

        void ifPresentOrElse(Consumer<? super T> consumer, Runnable action)

        This is a simple addition to the API.

        Proposal 2:

        Optional<T> ifPresent(Consumer<? super T> consumer)
        Optional<T> ifEmpty(Runnable action)

        This would require ifPresent to be changed to return the Optional<T>, to be able to chain the methods. Which would also be the downside of this proposal, because you would be able to chain multiple times, writing contrived code like: someOptional.ifPresent(...).ifEmpty(...).ifPresent(...).ifEmpty(...)
        (maybe this can be seen as a feature, but I think it's weird)

        Personally, I prefer proposal 1.

        JUSTIFICATION :
        Currently, when you want the behavior as in the description, you need to write code like:

        Optional<Item> nextItem = loadNextItem();
        if(nextItem.isPresent()) {
            nextItem.get().process();
        } else {
            latch.countDown();
        }

        or maybe:

        Optional<Item> nextItem = loadNextItem();
        nextItem.ifPresent(Item::process);
        if(!nextItem.isPresent()) {
            latch.countDown();
        }

        but these examples have issues:
        - both require you to declare a local variable to store the Optional
        - both somehow duplicate logic: you have the isPresent() check, plus the get() (1st example) or ifPresent() (2nd example)
        - they don't allow to use method references (except the if-part in the 2nd example)
        - the 2nd example is a bit shorter, but the if-else logic isn't as clear as in the 1st example


        EXPECTED VERSUS ACTUAL BEHAVIOR :
        EXPECTED -
        What I would like to write is:

        using proposal 1:

        loadNextItem().ifPresentOrElse(Item::process, latch::countDown);

        using proposal 2:

        loadNextItem().ifPresent(Item::process).ifEmpty(latch::countDown);

        ACTUAL -
        Actually there is no elegant way to do this.

          Attachments

            Issue Links

              Activity

                People

                • Assignee:
                  psandoz Paul Sandoz
                  Reporter:
                  webbuggrp Webbug Group
                • Votes:
                  0 Vote for this issue
                  Watchers:
                  3 Start watching this issue

                  Dates

                  • Created:
                    Updated:
                    Resolved: