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

Rewrite confusing stream API chain in SnippetMaps

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 17
    • None
    • tools
    • None
    • 17
    • b19

      After JDK-8263411, the stream call inside jdk.jshell.SnippetMaps::fullClassNameAndPackageToClass looks confusing:

              return Stream.concat(Stream.of("java.lang"), pkgs)
                           .filter(ipkg -> !ipkg.isEmpty() && ipkg.equals(pkg))
                           .map(ipkg -> full.substring(pkg.length() + 1))
                           .findFirst()
                           .orElse(full);

      The `map` step ignores the input element, so the subsequent stream content doesn't depend on the previous stream content. This looks like a misuse of stream API. In fact, using anyMatch here would be better:

              return Stream.concat(Stream.of("java.lang"), pkgs)
                           .anyMatch(ipkg -> !ipkg.isEmpty() && ipkg.equals(pkg))
                           ? full.substring(pkg.length() + 1) : full;

      Moreover, `!ipkg.isEmpty() && ipkg.equals(pkg)` is the same as `!pkg.isEmpty() && ipkg.equals(pkg)`, and as `!pkg.isEmpty()` check doesn't depend on the stream content, it could be extracted to a separate check. In case of empty package, stream is not necessary at all.

            tvaleev Tagir Valeev
            tvaleev Tagir Valeev
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: