11.5. 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
Write a method called
all
that returnstrue
if all the elements of an array pass a test supplied using a Predicate.public static <T> boolean all(T[] elements, Predicate<T> predicate) { ... } // all
Write a method called
any
that returnstrue
if at least one of the elements of an array passes a test supplied using a Predicate.public static <T> boolean any(T[] elements, Predicate<T> predicate) { ... } // any
Test Yourself Solutions (open after attempting the questions above)
One possible solution:
public static <T> boolean all(T[] elements, Predicate<T> predicate) { for (T t: elements) { if (!predicate.test(t)) { return false; // return false if an element doesn't pass the test } // if } // for // If we make it out of the loop, all elements passed the test return true; } // all
We won’t provide a solution to the second example above. Try it on your own, test it, and ask questions on Piazza if you get stuck. Feel free to share your code on Piazza since “Test Yourself” questions are not graded assignments.