Lambda Expressions in Java: transforming names to uppercase

Transforming Names to Uppercase In this example, we have a list of names: “John”, “Jane”, and “Alice”. We define a lambda expression String::toUpperCase and pass it as a Function<String, String> to the transformNames method. The lambda expression represents the toUpperCase method reference, which transforms a string to uppercase. The transformNames method takes a list of names and a Function<String, String> as arguments. It iterates over the names and applies the transformation using the apply method, printing the transformed names.

Extracting First Character of Names In this part of the example, we reuse the transformNames method to extract the first character of each name. We define a different lambda expression name -> name.substring(0, 1) and pass it as the transformer. This lambda expression takes a name and extracts the substring from index 0 to 1, representing the first character of the name. Again, the transformNames method iterates over the names and applies the transformation, printing the extracted first characters.

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class LambdasExample {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("John");
        names.add("Jane");
        names.add("Alice");

        // Title: Transforming Names to Uppercase
        System.out.println("Transformed Names (Uppercase):");
        transformNames(names, String::toUpperCase);

        // Title: Extracting First Character of Names
        System.out.println("Extracted First Characters:");
        transformNames(names, name -> name.substring(0, 1));
    }

    private static void transformNames(List<String> names, Function<String, String> transformer) {
        for (String name : names) {
            String transformedName = transformer.apply(name);
            System.out.println(transformedName);
        }
    }
}