Java Reference
In-Depth Information
Listing 5-8.
A Mapper Functional Interface
// Mapper.java
package com.jdojo.lambda;
@FunctionalInterface
public interface Mapper<T> {
// An abstract method
int map(T source);
// A generic static method
public static <U> int[] mapToInt(U[] list, Mapper<? super U> mapper) {
int[] mappedValues = new int[list.length];
for (int i = 0; i < list.length; i++) {
// Map the object to an int
mappedValues[i] = mapper.map(list[i]);
}
return mappedValues;
}
}
Mapper
is a generic functional interface with a type parameter
T
. Its abstract method
map()
takes an object of type
T
as a parameter and returns an
int
. The
mapToInt()
method is a generic static method that accepts an array of type
U
and a
Mapper
of a type that is
U
itself or a supertype of
U
. The method returns an
int
array whose elements contain the
mapped value for the corresponding elements passed as an array.
The program in Listing 5-9 shows how to use lambda expressions to instantiate the
Mapper<T>
interface.
The program maps a
String
array and an
Integer
array to
int
arrays.
Listing 5-9.
Using the Mapper Functional Interface
// MapperTest.java
package com.jdojo.lambda;
public class MapperTest {
public static void main(String[] args) {
// Map names using their length
System.out.println("Mapping names to their lengths:");
String[] names = {"David", "Li", "Doug"};
int[] lengthMapping = Mapper.mapToInt(names, (String name) -> name.length());
printMapping(names, lengthMapping);
System.out.println("\nMapping integers to their squares:");
Integer[] numbers = {7, 3, 67};
int[] countMapping = Mapper.mapToInt(numbers, (Integer n) -> n * n);
printMapping(numbers, countMapping);
}