Function.identity(): The Pass-Through Function
What you'll learn: How to use Java's built-in identity function that returns its input unchanged, and when this seemingly simple utility becomes surprisingly useful.
What is Function.identity()?
Function.identity() is a static method that returns a special function: one that simply returns whatever you pass into it, without any transformation. Think of it as a "do nothing" function—the input and output are identical.
Function<String, String> passThrough = Function.identity();
String result = passThrough.apply("Hello"); // Returns "Hello"
Why Does This Exist?
At first glance, this seems pointless. Why create a function that does nothing? The answer lies in functional programming patterns where you need to provide a Function instance, but you don't actually want to transform the data.
Common Use Cases
1. Map operations where you want keys as values:
List<String> names = Arrays.asList("Alice", "Bob", "Carol");
Map<String, String> map = names.stream()
.collect(Collectors.toMap(
Function.identity(), // Use name as key
name -> name.toUpperCase() // Transform for value
));
// Result: {"Alice"="ALICE", "Bob"="BOB", "Carol"="CAROL"}
2. Skipping transformation in a pipeline:
List<Integer> numbers = Arrays.asList(1, 2, 3);
Map<Integer, Integer> sameNumbers = numbers.stream()
.collect(Collectors.toMap(
Function.identity(), // Key is the number itself
Function.identity() // Value is also the number
));
identity() vs Lambda
While Function.identity() is equivalent to x -> x, using identity() is more expressive and memory-efficient—it returns the same singleton instance every time, rather than creating new lambda objects.
Key Takeaway: Function.identity() provides a reusable, self-documenting way to express "no transformation needed" in functional pipelines, commonly used when the input should serve as its own key or value.