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

add Map getter method that returns an Optional

    Details

      Description

      A DESCRIPTION OF THE PROBLEM :
      java.util.Map's getOrDefault() and putIfAbsent() methods are convenient to reduce the boilerplate code surrounding retrieval and adding data to a map in order to protect from null or unnecessarily adding existing data to a map. For my use case, we often times want to maintain a collection as the value in the map. For the simple case of reading the map, returning Collections.emptySet() for example is sufficient. However if we want to pull from the map to modify, calling getOrDefault(<key>, new HashSet<>()) adds additional memory overhead that needs to be garbage collected, especially if getOrDefault() could be called frequently when it rarely needs to actually return the default.

      My proposed solution would be to add overloaded methods for getOrDefault() and putIfAbsent() where the second parameter would be a lambda function that would be invoked only if the key wasn't in the Map. This lambda function would handle creating a new object of the value type and invoked only when needed. The various Java collections could implement this lambda function so that developers wouldn't have to implement it on their own. Developers would also have the option to create lambdas that support their own classes or other API classes.


        Attachments

          Activity

            People

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

              Dates

              • Created:
                Updated: