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

Add Support for a native findFirst() iterative List Collections

    XMLWordPrintable

Details

    Description

      A DESCRIPTION OF THE PROBLEM :
      It is currently either inefficient or syntactically awkward to get the first item in a collection in a stream, optional, or other functional component.

      Consider the following use case:

      ```java
      public class POJO {
         public List<String> codes;
      }
      ```

      And a simple use case:

      ```java
      public Optional<String> getFirstCodeSanitized(POJO pojo) {
         return Optional.ofNullable(pojo)
            .map(POJO::codes)
            .map(codes -> {
                if (codes == 0) return null;
                return codes.get(0);
            }) // codes -> codes.stream.findFirst() is a far less efficient but much nicer looking call
           .map(String::trim);
      }

      Expected:

      Much like the .forEach shortcut that collections provides; we could provides a simple list interface shortcut:

      ```java
      public default Optional<T> findFirst() {
         if (isEmpty()) {
            return Optional.empty();
         }
         return Optional.ofNullable(get(0));
      }
      ```

      This makes use of standard collections in functional operations far less awkward in the context of Records or POJOs.

      ```java
      public Optional<String> getFirstCodeSanitized(POJO pojo) {
         return Optional.ofNullable(pojo)
            .map(POJO::codes)
            .flatMap(List::findFirst)
           .map(String::trim);
      }

      I can of course make a static method that does this in my own code, but I feel that this a reasonably common use case that the common library should cover; at least specifically for peaking first item in the list functionally.


      Attachments

        Activity

          People

            smarks Stuart Marks
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: