Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-9337

DGM: more Optional and Stream extension methods

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 2.5.8, 3.0.0
    • 3.0.0-rc-3
    • None
    • None

    Description

      Follow up to GROOVY-8519.  Suggestions for new extension methods for Java 8's Optional and Stream:

      def opt = Optional.ofNullable(...)
      
      opt.filter(Type) // DGM that is shorthand for opt.filter(it -> it instanceof Type).map(it -> (Type) it) // result is Optional<Type>
      
      // methods available on Stream, but missing for Optional:
      opt.mapToInt(...) // DGM that accepts ToIntFunction and returns OptionalInt
      opt.mapToLong(...) // DGM that accepts ToLongFunction and returns OptionalLong
      opt.mapToDouble(...) // DGM that accepts ToDoubleFunction and returns OptionalDouble
      
      opt.stream() // DGM that is shorthand for opt.map(Stream::of).orElseGet(Stream::empty)
      // useful for Stream.concat() or generally interfacing with stream-based APIs
      
      // add get() to OptionalInt, OptionalLong and OptionalDouble as shorthand for getAsInt(), etc.
      
      OptionalInt optInt = ...
      optInt.filter(i -> ...) // accepts IntPredicate and returns OptionalInt.  Not sure why this is missing from OptionalInt, but this allows testing the value against some criteria.
      // similarly for OptionalLong and OptionalDouble
      
      def one = Stream.of(...)
      def two = Stream.of(...)
      def str = one + two // plus() overload for stream as shorthand for Stream.concat()
      str = str + obj // plus() overload for Stream.concat(str, obj.stream())
      
      str << obj // leftShift() overload; may make sense, may not
      
      def str2 = Stream.ofNullable(obj) // DGSM to return Stream.empty() for null and Stream.of(obj) for non-null -- exists in Java 9+
      
      // or maybe a general stream(Object) so you could do this instead:
      def str3 = obj.stream() // Stream.empty() for null and Stream.of(obj) for non-null
      

      Attachments

        Issue Links

          Activity

            People

              emilles Eric Milles
              emilles Eric Milles
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Time Tracking

                  Estimated:
                  Original Estimate - Not Specified
                  Not Specified
                  Remaining:
                  Remaining Estimate - 0h
                  0h
                  Logged:
                  Time Spent - 40m
                  40m