11.6. More Examples¶
In the code presented below, we create three more objects using lambda
expressions (four total). Using the usual named class approach to
implementing the interface would have required four .java
files,
one for each named class. Using the lambda expression approach, all
four (unnamed) classes are created and instantiated using a single
.java
file, and in this case, all in one method!
// Driver.java (assume proper package and import statements)
public class Driver {
public static void forEach(String[] strings, Consumer<String> consumer) {
for (int i = 0; i < strings.length; i++) {
String str = strings[i];
consumer.accept(str);
} // for
} // forEach
public static void main(String[] args) {
Consumer<String> println = t -> System.out.println(t);
Driver.forEach(args, println);
System.out.println();
Consumer<String> shout = t -> System.out.println(t.toUpperCase());
Driver.forEach(args, shout);
System.out.println();
Consumer<String> whisper = t -> System.out.println(t.toLowerCase());
Driver.forEach(args, whisper);
System.out.println();
Consumer<String> repeat2 = t -> System.out.println((t + " ").repeat(2));
Driver.forEach(args, repeat2);
System.out.println();
} // main
} // Driver
Compile ONE file, then run:
java Driver hello WORLD
hello
WORLD
HELLO
WORLD
hello
world
hello hello
WORLD WORLD
Test Yourself
In the API documentation for the preexisting Predicate interface, you will see that it contains an abstract method called
test
that takes a single parameter and returns a boolean value. You should also note that the interface is generic.Write a lambda expression to implement the
test
method so that it returns true if a providedString
is longer than 8 characters.
Test Yourself Solutions (open after attempting the questions above)
One possible solution:
Predicate<String> longString = (String s) -> { return s.length() > 8; };
Another valid solution:
Predicate<String> longString = (String s) -> { if (s.length() > 8) { return true; } else { return false; } // if };
Other solutions are possible.