BudiBadu Logo

Transform Strings Using References

Java Medium 12 views
Like17

Learn Java method references to write cleaner, more concise code by replacing lambda expressions with direct method references. You will use different forms of method references: static, instance, constructor, and arbitrary object methods.

Method references improve code readability when lambdas simply call existing methods. Understanding when to use them versus lambdas is key to writing idiomatic Java code.

Example 1:

Input: strings = ["hello", "world"]
Output: ["HELLO", "WORLD"]
Explanation: Use String::toUpperCase method reference.

Example 2:

Input: numbers = [1, 2, 3, 4, 5]
Output: [1, 4, 9, 16, 25]
Explanation: Use method reference for squaring.

Example 3:

Input: words = ["java", "python", "go"]
Output: 3
Explanation: Count using Collection::size reference.

Algorithm Flow

Recommendation Algorithm Flow for Transform Strings Using References - Budibadu
Recommendation Algorithm Flow for Transform Strings Using References - Budibadu

Best Answers

java - Approach 1
import java.util.List;
import java.util.stream.Collectors;

class Solution {
    public List<String> transformStrings(List<String> strings) {
        return strings.stream()
                     .map(String::toUpperCase)
                     .collect(Collectors.toList());
    }
}