Home> Java> javaTutorial> body text

Item Prefer references to methods over lambdas

王林
Release: 2024-07-19 14:02:39
Original
632 people have browsed it

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
Useless Parameter Removal:Parameters like count and incr are eliminated.
Example:

map.merge(key, 1, Integer::sum);
Copy after login
e

Efficient Use of References for Methods

  • Useful Documentation on Lambdas:In some cases, parameter names in lambdas can provide useful documentation.
  • Conversion from Lambdas to Methods:If a lambda is too complex, extract the code to 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!

source:dev.to
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!