Lambda Expressions

mixer

Java ≤ 7: Interface for Callbacks

Java ≤ 7: Interface for Callbacks (2)

Java ≤ 7: Interface for Callbacks (3)

Your Turn

Complete this program to compute the average length of the words that are entered in the input line. For example, if the input was

Bonjour le monde!

the program should print 5.0 (since (7 + 2 + 6)/3 = 5).

Make a class that implements the Measurable interface. Make an object of that class. Pass it to the average method.

Lambda Expressions

Lambda Expressions 2

Your Turn

Complete this program to compute the average length of the words that are entered in the input line. This time, use a lambda expression.

You'll need to cast obj to the appropriate type and apply a method.

Adding Generics

Parameter Type Inference

Your Turn

Put type inference to work by completing this program. Use a lambda expression that doesn't have a parameter type.

Exercises

  1. The Collection<T> interface has a method removeIf that accepts a Predicate<T>, a functional interface for a function T -> boolean. All elements for which the function is true are removed.

    Complete this program to remove all elements with length < 20 from a list of words.

  2. Complete this program to keep only the words that start and end with the same letter (ignoring letter case). Use a lambda expression of the form ... -> { ... }. Hint: substring, equalsIgnoreCase.

  3. One use for a Map<String, Integer> is to count how often a word occurs in a text. It is a bit tedious to deal with the special case of inserting the first value.

    Integer count = frequencies.get(word); // Get the old frequency count
    // If there was none, put 1; otherwise, increment the count
    if (count == null) { count = 1; }
    else { count = count + 1; }
    frequencies.put(word, count);

    Java 8 adds a useful merge method to the Map interface. You specify

    • A key
    • A value to be used if the key is not yet present.
    • A function to compute the updated value if the key is present.

    The function receives the old map value and the “not yet present” value, and it returns the new map value.

    frequencies.merge(word, 1, (oldValue, value) -> oldValue + value);

    The merge method is also useful if the map values are sets or comma-separated strings.

    Complete this program that tracks all lines on which a given word occurs. Remove the if statement and instead use a call to merge.

  4. Do the same in this program. Note that it's not quite so easy. You have two choices. Your function can compute and return the union of two sets. Or you can use merge just to make sure there is a set, and then call index.get(...).add(...).