Home >Java >javaTutorial >Item Prefer references to methods over lambdas

Item Prefer references to methods over lambdas

王林
王林Original
2024-07-19 14:02:39738browse

Advantages of References for Methods

  • Concision: References to methods are more concise than lambdas.
    Example: Increment value in a Map using merge:

  • Lambda: (count, incr) -> count + incr
    Reference for method: Integer::sum

Boilerplate Reduction
Removal of Useless Parameters: Parameters such as count and incr are eliminated.
Example:

map.merge(key, 1, Integer::sum);

Efficient Use of References for Methods

  • Useful Documentation in Lambdas: In some cases, parameter names in lambdas can provide useful documentation.
  • Conversion of Lambdas to Methods: If a lambda is too complex, extract the code into a separate method and use the reference to that method.

IDEs and References for Methods

  • IDE suggestions: IDEs often suggest replacing lambdas with references to methods.
  • Acceptance of Suggestions: Generally, accept suggestions, but evaluate on a case-by-case basis.

Exceptions and Considerations

  • More Concise Lambdas: Sometimes lambdas are more concise than method references.
  • Example with Class:
  • Reference for method: GoshThisClassNameIsHumongous::action
  • Lambda: () -> action()
  • Identity Function: Function.identity() vs. x -> x

Types of References for Methods

  • Static: Integer::parseInt (lambda: str -> Integer.parseInt(str))
  • Limited: Instant.now()::isAfter (lambda: t -> Instant.now().isAfter(t))
  • Unlimited: String::toLowerCase (lambda: str -> str.toLowerCase())
  • Class Constructor: TreeMap::new (lambda: () -> new TreeMap)
  • Array Constructor: int[]::new (lambda: len -> new int[len])

Conclusion
Preference for Method References: Use method references when they are shorter and clearer than lambdas.
Use of Lambdas: Prefer lambdas if they are more concise or provide better documentation.

Item  Dê preferência às referências para métodos em vez dos lambdas

The above is the detailed content of Item Prefer references to methods over lambdas. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn