11. Lambda Expressions Lesson

Lambda Expressions

Lambda Expressions

To see sample solutions, click on the "Configure activity" button and select "Show solutions" from the menu that appears.

Sample solutions not included, because "Show solutions" was not selected before printing.

Lesson Objectives

Motivate and introduce lambda Expressions.

Part 1: Another Generic max method?
Towards Generic Interfaces
Example 1: Drawable
The Drawable interface

Remember: Drawable was an interface that captured common functionality. All implementing classes have a draw method and can be drawn.

This interface is NOT generic.

Activity: Using the Drawable interface
public static void test(Drawable d) {
   d.______;
} // test

With your group, write which method(s) can be called using variable d. Then, write down where the code for the method(s) comes from.

Solution

Since any object that d refers to is an object of some class and all classes have java.lang.Object at the top of their hierarchy, we can call draw and all instance methods of the Object class using d.

However, since an interface is used as the datatype for d, it is probably the programmer's intention to call the method required by that interface inside the method.

Example 2: StringComparator
The StringComparator interface

Similarly, StringComparator captures the common functionality of comparing strings. All implementing classes contain a method called compare that allows two strings to be compared.

This interface is NOT generic.

public static void test(StringComparator sc) {
    sc.______;
} // test

With your group, write which method(s) can be called using variable sc. Then, write down where the code for the method(s) comes from.

Implement the StringComparator interface
Listing 132 The compare method in LengthComparator.
 1public class LengthComparator implements StringComparator {
 2
 3   /**
 4    * Compares its two arguments by length. Returns with a
 5    * negative integer if the first argument is shorter
 6    * than the second, zero if they are equal length, or
 7    * a positive integer if the first argument is longer
 8    * than the second.
 9    *
10    * @param o1 the first argument to compare.
11    * @param o2 the second argument to compare.
12    * @return the result of the length comparison.
13    */
14   @Override
15   public int compare(String o1, String o2) {
16       //
17       // your code here
18       //
19   } // compare
20
21} // LengthComparator

Write the code for the compare method in LengthComparator on your exit ticket (and in your own notes). Be sure to include the method signature. Do not include a Javadoc comment, unless you need it for your notes.

Sample Solution
public class LengthComparator implements StringComparator {

   @Override
   public int compare(String o1, String o2) {
       int length1 = o1.length();
       int length2 = o2.length();
       int result = length1 - length2;
       // negative: when length1 is shorter
       //    equal: when length1 is equal to length2
       // positive: when length2 is shorter
       return result;
   } // compare

} // LengthComparator
Example: Using our StringComparator implementation

With your groups, fill in the blanks below:

Listing 133 in class Utility
 1/**
 2 * Returns with a reference to the "max" String object in the array. We
 3 * define "max" as longest.
 4 *
 5 * @param items the array of strings to compare.
 6 * @param sc a reference to an object containing
 7 *     the compare method.
 8 * @return a reference to the "max" String object.
 9 */
10public static String max(String[] items, LengthComparator sc) {
11    String max = ________;
12    for (int i = 1; i < items.length; i++) {
13        String item = ________;
14        int result = ________;
15
16        if (result > 0) {
17            max = item;
18        } // if
19    } // for
20    return max;
21} // max
Solution
 1/**
 2 * Returns with a reference to the "max" String object in the array. We
 3 * define "max" as longest.
 4 *
 5 * @param items the array of strings to compare.
 6 * @param sc a reference to an object containing
 7 *     the compare method.
 8 * @return a reference to the "max" String object.
 9 */
10public static String max(String[] items, LengthComparator sc) {
11    String max = items[0];
12    for (int i = 1; i < items.length; i++) {
13        String item = items[i];
14        int result = sc.compare(item, max);
15        // negative: when item is considered shorter
16        //    equal: when item is considered equal to max
17        // positive: when item is considered greater
18        if (result > 0) {
19            max = item;
20        } // if
21    } // for
22    return max;
23} // max

Now, fill in the blanks below to call the max method on the provided string array:

1String[] strs = new String[] { "aa", "abc", "abcd", "a" };
2
3String max = ________; // call max here
4System.out.println(max); // should be abcd
Solution
Step 1 of 32: StringMaxExample.java:9
 1/** Run the length-based string comparator example. */
 2public class StringMaxExample {
 3
 4    /**
 5     * Run the example and print the longest string.
 6     * @param args unused command-line arguments
 7     */
 8    public static void main(String[] args) {
 9        String[] strs = new String[] { "aa", "abc", "abcd", "a" };
10        LengthComparator lc = new LengthComparator();
11
12        String max = Utility.max(strs, lc); // call max here
13        System.out.println(max); // should be abcd
14    } // main
15
16} // StringMaxExample
 1/** Compare strings by length. */
 2public class LengthComparator implements StringComparator {
 3
 4    /**
 5     * Compare the supplied strings by length.
 6     * @param o1 the first string
 7     * @param o2 the second string
 8     * @return a negative integer, zero, or a positive integer when the first
 9     *     string is shorter than, equal in length to, or longer than the second
10     */
11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
21
22} // LengthComparator
 1/** String utility methods for the comparator example. */
 2public class Utility {
 3
 4    /**
 5     * Return with a reference to the first longest string in the array.
 6     * @param items a nonempty array of non-null strings
 7     * @param sc the length comparator
 8     * @return a reference to the first longest string in the array
 9     */
10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
24
25} // Utility
 1/** Compare two strings according to an implementation's ordering. */
 2public interface StringComparator {
 3
 4    /**
 5     * Compare the supplied strings.
 6     * @param o1 the first string
 7     * @param o2 the second string
 8     * @return a negative integer, zero, or a positive integer when the first
 9     *     string is considered less than, equal to, or greater than the second
10     */
11    int compare(String o1, String o2);
12
13} // StringComparator
 8    public static void main(String[] args) {
 9        String[] strs = new String[] { "aa", "abc", "abcd", "a" };
10        LengthComparator lc = new LengthComparator();
11
12        String max = Utility.max(strs, lc); // call max here
13        System.out.println(max); // should be abcd
14    } // main
Code visualization diagram for StringMaxExample.java line 9

Memory state at the breakpoint on line 9 in StringMaxExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] strs = new String[] { "aa", "abc", "abcd", "a" };
10        LengthComparator lc = new LengthComparator();
11
12        String max = Utility.max(strs, lc); // call max here
13        System.out.println(max); // should be abcd
14    } // main
Code visualization diagram for StringMaxExample.java line 10

Memory state at the breakpoint on line 10 in StringMaxExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 1/** Compare strings by length. */
 2public class LengthComparator implements StringComparator {
 3
 4    /**
 5     * Compare the supplied strings by length.
 6     * @param o1 the first string
 7     * @param o2 the second string
 8     * @return a negative integer, zero, or a positive integer when the first
 9     *     string is shorter than, equal in length to, or longer than the second
10     */
11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
21
22} // LengthComparator
Code visualization diagram for LengthComparator.java line 2

Memory state at the breakpoint on line 2 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] strs = new String[] { "aa", "abc", "abcd", "a" };
10        LengthComparator lc = new LengthComparator();
11
12        String max = Utility.max(strs, lc); // call max here
13        System.out.println(max); // should be abcd
14    } // main
Code visualization diagram for StringMaxExample.java line 12

Memory state at the breakpoint on line 12 in StringMaxExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 11

Memory state at the breakpoint on line 11 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 12

Memory state at the breakpoint on line 12 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 13

Memory state at the breakpoint on line 13 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 14

Memory state at the breakpoint on line 14 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 13

Memory state at the breakpoint on line 13 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 14

Memory state at the breakpoint on line 14 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 15

Memory state at the breakpoint on line 15 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 19

Memory state at the breakpoint on line 19 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 18

Memory state at the breakpoint on line 18 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 19

Memory state at the breakpoint on line 19 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 13

Memory state at the breakpoint on line 13 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 14

Memory state at the breakpoint on line 14 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 13

Memory state at the breakpoint on line 13 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 14

Memory state at the breakpoint on line 14 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 15

Memory state at the breakpoint on line 15 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 19

Memory state at the breakpoint on line 19 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 18

Memory state at the breakpoint on line 18 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 19

Memory state at the breakpoint on line 19 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 13

Memory state at the breakpoint on line 13 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 14

Memory state at the breakpoint on line 14 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 13

Memory state at the breakpoint on line 13 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 14

Memory state at the breakpoint on line 14 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 15

Memory state at the breakpoint on line 15 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 19

Memory state at the breakpoint on line 19 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 18

Memory state at the breakpoint on line 18 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

10    public static String max(String[] items, LengthComparator sc) {
11        String max = items[0];
12        for (int i = 1; i < items.length; i++) {
13            String item = items[i];
14            int result = sc.compare(item, max);
15            // negative: when item is considered shorter
16            //    equal: when item is considered equal to max
17            // positive: when item is considered greater
18            if (result > 0) {
19                max = item;
20            } // if
21        } // for
22        return max;
23    } // max
Code visualization diagram for Utility.java line 22

Memory state at the breakpoint on line 22 in Utility.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] strs = new String[] { "aa", "abc", "abcd", "a" };
10        LengthComparator lc = new LengthComparator();
11
12        String max = Utility.max(strs, lc); // call max here
13        System.out.println(max); // should be abcd
14    } // main
Code visualization diagram for StringMaxExample.java line 13

Memory state at the breakpoint on line 13 in StringMaxExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] strs = new String[] { "aa", "abc", "abcd", "a" };
10        LengthComparator lc = new LengthComparator();
11
12        String max = Utility.max(strs, lc); // call max here
13        System.out.println(max); // should be abcd
14    } // main
Code visualization diagram for StringMaxExample.java line 14

Memory state at the breakpoint on line 14 in StringMaxExample.java. [code listing] [download] [open]

abcd

>_ Console Output

Improving the max method
Activity: Multiple max methods
public static String max(String[] items, LengthComparator sc) {
      String max = items[0];
      for (int i = 1; i < items.length; i++) {
          String item = items[i];
          int result = sc.compare(item, max);
          if (result > 0) {
              max = item;
          } // if
      } // for
      return max;
} // max
public static String max(String[] items, VowelCountComparator sc) {
      String max = items[0];
      for (int i = 1; i < items.length; i++) {
          String item = items[i];
          int result = sc.compare(item, max);
          if (result > 0) {
              max = item;
          } // if
      } // for
      return max;
} // max

Can we write max once and in a way that allows us to plug in different StringComparator implementations, regardless of whether that implementation is a LengthComparator, VowelCountComparator, or something else?

With your group, write the method signature for a version of the max method that works with LengthComparator, VowelCountComparator, and other kinds of StringComparator implementations. You only need to write down the signature.

Sample Solution: One max method
public static String max(String[] items, StringComparator sc) { ...
Discussion: Using our max method
Listing 134 Assume this is in class Driver
public static String max(String[] items, StringComparator sc) { ...

How would we call our new max method in the blanks below?

String[] items = ...; // Assume the array is properly instantiated and holds multiple strings

String longest = _____________; // Call max here

String mostVowels = ____________; // Call max here
Sample Solution

The array contains "cat", "boat", "queue", and "elephant". Their lengths are 3, 4, 5, and 8; their vowel counts are 1, 2, 4, and 3. Here, vowels are a, e, i, o, and u in either case.

Step 1 of 61: Driver.java:9
 1/** Select strings with different comparison strategies. */
 2public class Driver {
 3
 4    /**
 5     * Run the example and print the two selected strings.
 6     * @param args unused command-line arguments
 7     */
 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
19
20    /**
21     * Return with a reference to the first greatest string under the comparator.
22     * @param items a nonempty array of non-null strings
23     * @param sc the comparator defining the ordering
24     * @return a reference to the first greatest string under the comparator
25     */
26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
37
38} // Driver
 1/** Compare strings by length. */
 2public class LengthComparator implements StringComparator {
 3
 4    /**
 5     * Compare the supplied strings by length.
 6     * @param o1 the first string
 7     * @param o2 the second string
 8     * @return a negative integer, zero, or a positive integer when the first
 9     *     string is shorter than, equal in length to, or longer than the second
10     */
11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
21
22} // LengthComparator
 1/** Compare two strings according to an implementation's ordering. */
 2public interface StringComparator {
 3
 4    /**
 5     * Compare the supplied strings.
 6     * @param o1 the first string
 7     * @param o2 the second string
 8     * @return a negative integer, zero, or a positive integer when the first
 9     *     string is considered less than, equal to, or greater than the second
10     */
11    int compare(String o1, String o2);
12
13} // StringComparator
 1/** Compare strings by their number of ASCII vowels. */
 2public class VowelCountComparator implements StringComparator {
 3
 4    /**
 5     * Compare the supplied strings by their vowel counts.
 6     * @param o1 the first string
 7     * @param o2 the second string
 8     * @return a negative integer, zero, or a positive integer when the first
 9     *     string has fewer vowels, the same count, or more vowels than the second
10     */
11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
18
19    /**
20     * Count occurrences of a, e, i, o, and u in either case.
21     * @param text a non-null string
22     * @return the number of ASCII vowel occurrences
23     */
24    private static int countVowels(String text) {
25        int count = 0;
26        for (int index = 0; index < text.length(); index++) {
27            char letter = text.charAt(index);
28            boolean vowel = letter == 'a' || letter == 'A'
29                || letter == 'e' || letter == 'E'
30                || letter == 'i' || letter == 'I'
31                || letter == 'o' || letter == 'O'
32                || letter == 'u' || letter == 'U';
33            if (vowel) {
34                count++;
35            } // if
36        } // for
37        return count;
38    } // countVowels
39
40} // VowelCountComparator
 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 9

Memory state at the breakpoint on line 9 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 11

Memory state at the breakpoint on line 11 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 12

Memory state at the breakpoint on line 12 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 27

Memory state at the breakpoint on line 27 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 28

Memory state at the breakpoint on line 28 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 29

Memory state at the breakpoint on line 29 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 30

Memory state at the breakpoint on line 30 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 13

Memory state at the breakpoint on line 13 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 14

Memory state at the breakpoint on line 14 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 15

Memory state at the breakpoint on line 15 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 19

Memory state at the breakpoint on line 19 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 31

Memory state at the breakpoint on line 31 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 32

Memory state at the breakpoint on line 32 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 29

Memory state at the breakpoint on line 29 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 30

Memory state at the breakpoint on line 30 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 13

Memory state at the breakpoint on line 13 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 14

Memory state at the breakpoint on line 14 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 15

Memory state at the breakpoint on line 15 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 19

Memory state at the breakpoint on line 19 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 31

Memory state at the breakpoint on line 31 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 32

Memory state at the breakpoint on line 32 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 29

Memory state at the breakpoint on line 29 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 30

Memory state at the breakpoint on line 30 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 13

Memory state at the breakpoint on line 13 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 14

Memory state at the breakpoint on line 14 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 15

Memory state at the breakpoint on line 15 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int length1 = o1.length();
14        int length2 = o2.length();
15        int result = length1 - length2;
16        // negative: when length1 is shorter
17        //    equal: when length1 is equal to length2
18        // positive: when length2 is shorter
19        return result;
20    } // compare
Code visualization diagram for LengthComparator.java line 19

Memory state at the breakpoint on line 19 in LengthComparator.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 31

Memory state at the breakpoint on line 31 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 32

Memory state at the breakpoint on line 32 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 35

Memory state at the breakpoint on line 35 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 13

Memory state at the breakpoint on line 13 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 15

Memory state at the breakpoint on line 15 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 16

Memory state at the breakpoint on line 16 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 27

Memory state at the breakpoint on line 27 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 28

Memory state at the breakpoint on line 28 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 29

Memory state at the breakpoint on line 29 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 30

Memory state at the breakpoint on line 30 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 13

Memory state at the breakpoint on line 13 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 14

Memory state at the breakpoint on line 14 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 15

Memory state at the breakpoint on line 15 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 16

Memory state at the breakpoint on line 16 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 31

Memory state at the breakpoint on line 31 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 32

Memory state at the breakpoint on line 32 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 29

Memory state at the breakpoint on line 29 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 30

Memory state at the breakpoint on line 30 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 13

Memory state at the breakpoint on line 13 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 14

Memory state at the breakpoint on line 14 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 15

Memory state at the breakpoint on line 15 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 16

Memory state at the breakpoint on line 16 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 31

Memory state at the breakpoint on line 31 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 32

Memory state at the breakpoint on line 32 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 29

Memory state at the breakpoint on line 29 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 30

Memory state at the breakpoint on line 30 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 13

Memory state at the breakpoint on line 13 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 14

Memory state at the breakpoint on line 14 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 15

Memory state at the breakpoint on line 15 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

11    @Override
12    public int compare(String o1, String o2) {
13        int count1 = countVowels(o1);
14        int count2 = countVowels(o2);
15        int result = count1 - count2;
16        return result;
17    } // compare
Code visualization diagram for VowelCountComparator.java line 16

Memory state at the breakpoint on line 16 in VowelCountComparator.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 31

Memory state at the breakpoint on line 31 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

26    public static String max(String[] items, StringComparator sc) {
27        String max = items[0];
28        for (int i = 1; i < items.length; i++) {
29            String item = items[i];
30            int result = sc.compare(item, max);
31            if (result > 0) {
32                max = item;
33            } // if
34        } // for
35        return max;
36    } // max
Code visualization diagram for Driver.java line 35

Memory state at the breakpoint on line 35 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 17

Memory state at the breakpoint on line 17 in Driver.java. [code listing] [download] [open]

elephant

>_ Console Output

 8    public static void main(String[] args) {
 9        String[] items = new String[] { "cat", "boat", "queue", "elephant" };
10
11        StringComparator byLength = new LengthComparator();
12        String longest = Driver.max(items, byLength);
13        System.out.println(longest);
14
15        StringComparator byVowelCount = new VowelCountComparator();
16        String mostVowels = Driver.max(items, byVowelCount);
17        System.out.println(mostVowels);
18    } // main
Code visualization diagram for Driver.java line 18

Memory state at the breakpoint on line 18 in Driver.java. [code listing] [download] [open]

elephant
queue

>_ Console Output

The program prints elephant and then queue. The stepper follows both calls to max and their comparator method calls. Use Show full source to inspect the vowel-counting helper.

It's "plug and play" since we used an interface.

Discussion: One more update to max (1)

What is a limitation of the current max method? How could we improve it?

public static String max(String[] items, StringComparator comp) {
Hint

Can we write one method that works for all reference types?

public static String max(String[] items, StringComparator comp) { ...
public static Song max(Song[] items, SongComparator comp) { ...
public static Person max(Person[] items, PersonComparator comp) { ...
public static Dog max(Dog[] items, DogComparator comp) { ...
Example 3: Comparator<T>
Activity: A better max method
public static String max(String[] items, StringComparator comp) { ...
public static Song max(Song[] items, SongComparator comp) { ...
public static Person max(Person[] items, PersonComparator comp) { ...
public static Dog max(Dog[] items, DogComparator comp) { ...

With your group, write the method signature for a version of the max method that works for any reference type. You only need to write down the signature.

Sample Solution: A better max method
public static <T> T max(T[] items, Comparator<T> comp) { ...

This assumes that all the objects referred to by comp are adjusted so that they implement Comparator<T>, an interface that you were exposed to when you did the reading for your latest project.

Instead of separate interfaces, each class can implement Comparator<T>, since the signature for each of their compare method is the same. To bring everything together, we make the following adjustments:

  • implements StringComparator to implements Comparator<String>

  • implements SongComparator to implements Comparator<Song>

  • implements PersonComparator to implements Comparator<Person>

  • implements DogComparator to implements Comparator<Dog>

Activity: Write the generic max method
public static <T> T max(T[] items, Comparator<T> comp) {
   T maxItem = ________;                       // Line 1
   for (int i = 1; i < items.length; i++) {
       T item = ________;                      // Line 2
       int result = _______;                   // Line 3
       if (result > 0) {
           maxItem = item;
       } // if
   } // for
   return maxItem;
} // max

Write the code for the max method on your exit ticket (and in your own notes). Be sure to include the method signature. Do not include a Javadoc comment, unless you need it for your notes.

Sample Solution: The generic max method
public static <T> T max(T[] items, Comparator<T> comp) {
    T maxItem = items[0];
    for (int i = 1; i < items.length; i++) {
        T item = items[i];
        int result = comp.compare(item, maxItem);
        if (result > 0) {
            maxItem = item;
        } // if
    } // for
    return maxItem;
} // max

Another version for linked lists:

public static <T> T max(Node<T> head, Comparator<T> comp) {
    T maxItem = head.getItem();
    while (head != null) {
        T item = head.getItem();
        int result = comp.compare(item, maxItem);
        if (result > 0) {
            maxItem = item;
        } // if
        head = head.getNext();
    } // while
    return maxItem;
} // max
Part 2: Functional Interfaces
Examples: Implementing the Comparator<T> interface

Here, we show how we can implement Comparator<T> using a regular class and how we transition from a regular class to an anonymous class to a lambda expression.

The demos below use the Person and Movie classes supplied with the Urgency Queue Project.

Example: Person by age() (ascending)
public class PersonAgeComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.age() - o2.age();
    } // compare

} // PersonAgeComparator
public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byAge = new PersonAgeComparator();

    Person oldest = Driver.<Person>max(persons, byAge);

    ...

} // main
public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byAge = new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.age() - o2.age();
        } // compare
    };

    Person oldest = Driver.<Person>max(persons, byAge);

    ...

} // main

Warning

Although the code above will compile, use of anonymous class syntax is highly discouraged, because it includes almost the same amount of boilerplate as the regular class version.

public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byAge = public int compare(Person o1, Person o2) {
        return o1.age() - o2.age();
    };

    Person oldest = Driver.<Person>max(persons, byAge);

    ...

} // main

Warning

The code above will NOT compile, but writing it like that makes it clear that we are still overriding the compare method in whatever object byAge ends up referring to…

public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byAge = (Person o1, Person o2) -> {
        return o1.age() - o2.age();
    };

    Person oldest = Driver.<Person>max(persons, byAge);

    ...

} // main

Important

A lambda expression can only be assigned to a variable with a functional interface as its type. Why?

Warning

There are shorter ways to write the lambda expression shown above, but the version shown above looks more like a method, and everyone in the room has experience writing methods. Don't try to move too fast. Once you are comfortable writing lambda expressions like the one above, we will start using the shorter syntax.

Lambda Expression Demo

The array contains Mia (35), Zoe (21), and Ada (42), in that order. Comparing by age selects Ada, the oldest person.

Step 1 of 17: PersonAgeExample.java:14
 1package cs1302.lambda;
 2
 3import cs1302.oracle.model.Person;
 4import java.util.Comparator;
 5
 6/** Compare supplied person records by age using an explicitly typed lambda. */
 7public class PersonAgeExample {
 8
 9    /**
10     * Select the oldest of three people and print the person's name.
11     * @param args unused command-line arguments
12     */
13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
27
28} // PersonAgeExample
 1package cs1302.lambda;
 2
 3import java.util.Comparator;
 4import java.util.function.Predicate;
 5
 6/** Select array elements using supplied comparators and predicates. */
 7public class Driver {
 8
 9    /**
10     * Return with a reference to the first greatest element under the comparator.
11     * @param <T> the array element type
12     * @param items a nonempty array of non-null elements
13     * @param comp the comparator defining the ordering
14     * @return a reference to the first greatest element under the comparator
15     */
16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
27
28    /**
29     * Prints the array elements that pass the predicate's test, one per line.
30     *
31     * @param <T> the array element type
32     * @param items the specified array
33     * @param condition the specified predicate
34     */
35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
43
44} // Driver
13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 14

Memory state at the breakpoint on line 14 in PersonAgeExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 20

Memory state at the breakpoint on line 20 in PersonAgeExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 24

Memory state at the breakpoint on line 24 in PersonAgeExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 17

Memory state at the breakpoint on line 17 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 18

Memory state at the breakpoint on line 18 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 19

Memory state at the breakpoint on line 19 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 20

Memory state at the breakpoint on line 20 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 21

Memory state at the breakpoint on line 21 in PersonAgeExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 21

Memory state at the breakpoint on line 21 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 19

Memory state at the breakpoint on line 19 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 20

Memory state at the breakpoint on line 20 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 21

Memory state at the breakpoint on line 21 in PersonAgeExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 21

Memory state at the breakpoint on line 21 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 22

Memory state at the breakpoint on line 22 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 25

Memory state at the breakpoint on line 25 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 25

Memory state at the breakpoint on line 25 in PersonAgeExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byAge = (Person o1, Person o2) -> {
21            return o1.age() - o2.age();
22        };
23
24        Person oldest = Driver.<Person>max(persons, byAge);
25        System.out.println("Oldest: " + oldest.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonAgeExample.java line 26

Memory state at the breakpoint on line 26 in PersonAgeExample.java. [code listing] [download] [open]

Oldest: Ada

>_ Console Output

Example: Person by name() (ascending)
public class PersonNameComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.name().compareTo(o2.name());
    } // compare

} // PersonNameComparator
public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byName = new PersonNameComparator();

    Person last = Driver.<Person>max(persons, byName);

    ...

} // main
public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byName = new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.name().compareTo(o2.name());
        } // compare
    };

    Person last = Driver.<Person>max(persons, byName);

    ...

} // main

Warning

Although the code above will compile, use of anonymous class syntax is highly discouraged, because it includes almost the same amount of boilerplate as the regular class version.

public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byName = public int compare(Person o1, Person o2) {
        return o1.name().compareTo(o2.name());
    };

    Person last = Driver.<Person>max(persons, byName);

    ...

} // main

Warning

The code above will NOT compile, but writing it like that makes it clear that we are still overriding the compare method in whatever object byName ends up referring to…

public static void main(String[] args) {

    Person[] persons = ...;

    Comparator<Person> byName = (Person o1, Person o2) -> {
        return o1.name().compareTo(o2.name());
    };

    Person last = Driver.<Person>max(persons, byName);

    ...

} // main

Important

A lambda expression can only be assigned to a variable with a functional interface as its type. Why?

Warning

There are shorter ways to write the lambda expression shown above, but the version shown above looks more like a method, and everyone in the room has experience writing methods. Don't try to move too fast. Once you are comfortable writing lambda expressions like the one above, we will start using the shorter syntax.

Lambda Expression Demo

This array contains the same three people in the same order. Comparing by name selects Zoe, whose name comes last in lexicographic order, rather than Ada, the oldest person.

Step 1 of 17: PersonNameExample.java:14
 1package cs1302.lambda;
 2
 3import cs1302.oracle.model.Person;
 4import java.util.Comparator;
 5
 6/** Compare supplied person records by name using an explicitly typed lambda. */
 7public class PersonNameExample {
 8
 9    /**
10     * Select the lexicographically greatest person name and print it.
11     * @param args unused command-line arguments
12     */
13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
27
28} // PersonNameExample
 1package cs1302.lambda;
 2
 3import java.util.Comparator;
 4import java.util.function.Predicate;
 5
 6/** Select array elements using supplied comparators and predicates. */
 7public class Driver {
 8
 9    /**
10     * Return with a reference to the first greatest element under the comparator.
11     * @param <T> the array element type
12     * @param items a nonempty array of non-null elements
13     * @param comp the comparator defining the ordering
14     * @return a reference to the first greatest element under the comparator
15     */
16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
27
28    /**
29     * Prints the array elements that pass the predicate's test, one per line.
30     *
31     * @param <T> the array element type
32     * @param items the specified array
33     * @param condition the specified predicate
34     */
35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
43
44} // Driver
13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 14

Memory state at the breakpoint on line 14 in PersonNameExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 20

Memory state at the breakpoint on line 20 in PersonNameExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 24

Memory state at the breakpoint on line 24 in PersonNameExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 17

Memory state at the breakpoint on line 17 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 18

Memory state at the breakpoint on line 18 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 19

Memory state at the breakpoint on line 19 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 20

Memory state at the breakpoint on line 20 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 21

Memory state at the breakpoint on line 21 in PersonNameExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 21

Memory state at the breakpoint on line 21 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 22

Memory state at the breakpoint on line 22 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 19

Memory state at the breakpoint on line 19 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 20

Memory state at the breakpoint on line 20 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 21

Memory state at the breakpoint on line 21 in PersonNameExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 21

Memory state at the breakpoint on line 21 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
Code visualization diagram for cs1302/lambda/Driver.java line 25

Memory state at the breakpoint on line 25 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 25

Memory state at the breakpoint on line 25 in PersonNameExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        Person[] persons = {
15            new Person(35, "Mia"),
16            new Person(21, "Zoe"),
17            new Person(42, "Ada")
18        };
19
20        Comparator<Person> byName = (Person o1, Person o2) -> {
21            return o1.name().compareTo(o2.name());
22        };
23
24        Person last = Driver.<Person>max(persons, byName);
25        System.out.println("Last by name: " + last.name());
26    } // main
Code visualization diagram for cs1302/lambda/PersonNameExample.java line 26

Memory state at the breakpoint on line 26 in PersonNameExample.java. [code listing] [download] [open]

Last by name: Zoe

>_ Console Output

Example: Movie by various (ascending; lambda)
public static void main(String[] args) {

    Movie[] movies = ...;

    Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
        return o1.year().compareTo(o2.year());
    };

    Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
        return o1.rating() - o2.rating();
    };

    Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
        return o1.runtime().compareTo(o2.runtime());
    };

    Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
        return o1.cast().size() - o2.cast().size();
    };

    Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
        return o1.tagline().length() - o2.tagline().length();
    };

    ...

} // main
Lambda Expression Demo

The array contains three fictional movies. Each call to max uses the same array with a different comparator.

Table 3 Movie comparison data

Movie

Year

Rating

Runtime (minutes)

Cast size

Tagline

Aster

2005

7

110

3

Go.

Beacon

1998

9

95

1

Find a way.

Cedar

2012

8

130

2

Head home.

Step 1 of 39: MovieComparatorExample.java:18
 1package cs1302.lambda;
 2
 3import cs1302.oracle.model.Movie;
 4import java.time.Duration;
 5import java.time.Year;
 6import java.util.Comparator;
 7import java.util.List;
 8import java.util.Set;
 9
10/** Compare three movies using five explicitly typed lambdas. */
11public class MovieComparatorExample {
12
13    /**
14     * Print the selected movie's name for each comparison criterion.
15     * @param args unused command-line arguments
16     */
17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
51
52    /**
53     * Construct three synthetic movies using the supplied movie record class.
54     * @return a reference to an array containing exactly three movie reference values
55     */
56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
72
73} // MovieComparatorExample
 1package cs1302.lambda;
 2
 3import java.util.Comparator;
 4import java.util.function.Predicate;
 5
 6/** Select array elements using supplied comparators and predicates. */
 7public class Driver {
 8
 9    /**
10     * Return with a reference to the first greatest element under the comparator.
11     * @param <T> the array element type
12     * @param items a nonempty array of non-null elements
13     * @param comp the comparator defining the ordering
14     * @return a reference to the first greatest element under the comparator
15     */
16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
27
28    /**
29     * Prints the array elements that pass the predicate's test, one per line.
30     *
31     * @param <T> the array element type
32     * @param items the specified array
33     * @param condition the specified predicate
34     */
35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
43
44} // Driver
17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 18

Memory state at the breakpoint on line 18 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 57

Memory state at the breakpoint on line 57 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 58

Memory state at the breakpoint on line 58 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 59

Memory state at the breakpoint on line 59 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 60

Memory state at the breakpoint on line 60 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 62

Memory state at the breakpoint on line 62 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 63

Memory state at the breakpoint on line 63 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 64

Memory state at the breakpoint on line 64 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 65

Memory state at the breakpoint on line 65 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 66

Memory state at the breakpoint on line 66 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 67

Memory state at the breakpoint on line 67 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 68

Memory state at the breakpoint on line 68 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

56    private static Movie[] createMovies() {
57        return new Movie[] {
58            new Movie("Aster", Year.of(2005), 7, List.of(Movie.Genre.DRAMA),
59                Duration.ofMinutes(110), "Go.",
60                Set.of(new Movie.Member("Avery"), new Movie.Member("Blair"),
61                    new Movie.Member("Casey")),
62                Set.of(), Set.of()),
63            new Movie("Beacon", Year.of(1998), 9, List.of(Movie.Genre.DRAMA),
64                Duration.ofMinutes(95), "Find a way.",
65                Set.of(new Movie.Member("Drew")), Set.of(), Set.of()),
66            new Movie("Cedar", Year.of(2012), 8, List.of(Movie.Genre.DRAMA),
67                Duration.ofMinutes(130), "Head home.",
68                Set.of(new Movie.Member("Ellis"), new Movie.Member("Finley")),
69                Set.of(), Set.of())
70        };
71    } // createMovies
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 69

Memory state at the breakpoint on line 69 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 20

Memory state at the breakpoint on line 20 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 24

Memory state at the breakpoint on line 24 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 28

Memory state at the breakpoint on line 28 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 32

Memory state at the breakpoint on line 32 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 36

Memory state at the breakpoint on line 36 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 40

Memory state at the breakpoint on line 40 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 21

Memory state at the breakpoint on line 21 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 21

Memory state at the breakpoint on line 21 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 41

Memory state at the breakpoint on line 41 in MovieComparatorExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 42

Memory state at the breakpoint on line 42 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 25

Memory state at the breakpoint on line 25 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 25

Memory state at the breakpoint on line 25 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 43

Memory state at the breakpoint on line 43 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 44

Memory state at the breakpoint on line 44 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 29

Memory state at the breakpoint on line 29 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 29

Memory state at the breakpoint on line 29 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 45

Memory state at the breakpoint on line 45 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 46

Memory state at the breakpoint on line 46 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 33

Memory state at the breakpoint on line 33 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 33

Memory state at the breakpoint on line 33 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 47

Memory state at the breakpoint on line 47 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 48

Memory state at the breakpoint on line 48 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar
Cast size: Aster

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 37

Memory state at the breakpoint on line 37 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar
Cast size: Aster

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 37

Memory state at the breakpoint on line 37 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar
Cast size: Aster

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 49

Memory state at the breakpoint on line 49 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar
Cast size: Aster

>_ Console Output

17    public static void main(String[] args) {
18        Movie[] movies = createMovies();
19
20        Comparator<Movie> byYear = (Movie o1, Movie o2) -> {
21            return o1.year().compareTo(o2.year());
22        };
23
24        Comparator<Movie> byRating = (Movie o1, Movie o2) -> {
25            return o1.rating() - o2.rating();
26        };
27
28        Comparator<Movie> byRuntime = (Movie o1, Movie o2) -> {
29            return o1.runtime().compareTo(o2.runtime());
30        };
31
32        Comparator<Movie> byCastSize = (Movie o1, Movie o2) -> {
33            return o1.cast().size() - o2.cast().size();
34        };
35
36        Comparator<Movie> byTaglineLength = (Movie o1, Movie o2) -> {
37            return o1.tagline().length() - o2.tagline().length();
38        };
39
40        Movie newest = Driver.<Movie>max(movies, byYear);
41        System.out.println("Year: " + newest.name());
42        Movie highestRated = Driver.<Movie>max(movies, byRating);
43        System.out.println("Rating: " + highestRated.name());
44        Movie longest = Driver.<Movie>max(movies, byRuntime);
45        System.out.println("Runtime: " + longest.name());
46        Movie largestCast = Driver.<Movie>max(movies, byCastSize);
47        System.out.println("Cast size: " + largestCast.name());
48        Movie longestTagline = Driver.<Movie>max(movies, byTaglineLength);
49        System.out.println("Tagline length: " + longestTagline.name());
50    } // main
Code visualization diagram for cs1302/lambda/MovieComparatorExample.java line 50

Memory state at the breakpoint on line 50 in MovieComparatorExample.java. [code listing] [download] [open]

Year: Cedar
Rating: Beacon
Runtime: Cedar
Cast size: Aster
Tagline length: Beacon

>_ Console Output

The selected movies are Cedar by year, Beacon by rating, Cedar by runtime, Aster by cast size, and Beacon by tagline length. The stepper follows movie construction and the lambda bodies in MovieComparatorExample.java, with no stops inside Driver.max. Use open beneath the diagram for a larger view.

Discussion: How this relates to P3

The two versions of the max method we have developed over the past two chapters demonstrate the two ways you are expected to compare items for the Urgency Queue Project (P3). Take a look at the UML diagram for P3 and discuss how using a Comparator and a bounded type parameter relates. Make sure you focus on the differences between the child classes and understand how they work.

Activity: Exploring the Predicate<T> interface

To get started: search for "Java Predicate" to pull up the Java API page for java.util.function.Predicate<T>…

Predicate<String> longerThan10 = (String t) -> {
   return t.length() > 10;
};

Answer the following questions about the code above on your exit ticket (and in your notes):

  1. Which abstract method declared in Predicate is being implemented by the lambda expression above? You may need to check the Java API to get the exact name.

  2. What method can we call using longerThan10 as the calling object?

  3. Using longerThan10, write code that prints whether or not "Hello, World" contains more than 10 characters.

Sample Solution: Exploring the Predicate<T> interface
Step 1 of 6: PredicateExample.java:16
 1package cs1302.lambda;
 2
 3import java.util.function.Predicate;
 4
 5/**
 6 * Demonstrates testing string lengths with a predicate implemented by a lambda.
 7 */
 8public class PredicateExample {
 9
10    /**
11     * Tests two strings and prints the results.
12     *
13     * @param args the command-line arguments
14     */
15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
22
23} // PredicateExample
15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
Code visualization diagram for cs1302/lambda/PredicateExample.java line 16

Memory state at the breakpoint on line 16 in PredicateExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
Code visualization diagram for cs1302/lambda/PredicateExample.java line 19

Memory state at the breakpoint on line 19 in PredicateExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
Code visualization diagram for cs1302/lambda/PredicateExample.java line 17

Memory state at the breakpoint on line 17 in PredicateExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
Code visualization diagram for cs1302/lambda/PredicateExample.java line 20

Memory state at the breakpoint on line 20 in PredicateExample.java. [code listing] [download] [open]

false

>_ Console Output

15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
Code visualization diagram for cs1302/lambda/PredicateExample.java line 17

Memory state at the breakpoint on line 17 in PredicateExample.java. [code listing] [download] [open]

false

>_ Console Output

15    public static void main(String[] args) {
16        Predicate<String> longerThan10 = (String t) -> {
17            return t.length() > 10;
18        };
19        System.out.println(longerThan10.test("hello"));
20        System.out.println(longerThan10.test("hello, world"));
21    } // main
Code visualization diagram for cs1302/lambda/PredicateExample.java line 21

Memory state at the breakpoint on line 21 in PredicateExample.java. [code listing] [download] [open]

false
true

>_ Console Output

Discussion: The <T>printlnMatches method
/**
 * Prints the elements of the array that pass the test specified by the given
 * predicate. Each element will be printed on its own
 * line.
 *
 * @param <T> the type of the array elements
 * @param items the specified array
 * @param condition the specified predicate
 */
public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
   throw new UnsupportedOperationException("not yet implemented");
} // printlnMatches

Suppose we want to implement the printlnMatches method above.

  • Is the method printlnMatches a generic method? How can you tell?

  • What method can we call using condition as the calling object?

Solution
  • Yes. It has a type parameter, T

  • condition is a reference to an object of a class that implements Predicate<T>. Therefore, it is guaranteed to have a test method.

Activity: Writing the <T>printlnMatches method
/**
 * Prints the elements of the array that pass the test specified by the given
 * predicate. Each element will be printed on its own
 * line.
 *
 * @param <T> the type of the array elements
 * @param items the specified array
 * @param condition the specified predicate
 */
public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
   throw new UnsupportedOperationException("not yet implemented");
} // printlnMatches

Write the code for the printlnMatches method on your exit ticket (and in your own notes). Be sure to include the method signature. Do not include a Javadoc comment, unless you need it for your notes.

Sample Solution: Writing the <T>printlnMatches method
public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
    for (int i = 0; i < items.length; i++) {
        T item = items[i];
        if (condition.test(item)) {
            System.out.println(item);
        } // if
    } // for
} // printlnMatches
Activity: Calling the <T>printlnMatches method

Finish the code below so that printlnMatches prints all strings containing the letter a:

String[] myStrings = new String[] {
   "CSCI", "1302", "is", "an", "awesome", "course!"
};

Predicate<String> containsA = _____________;         // Blank 1

Driver.<String>printlnMatches(_________, _________); // Blanks 2 and 3
Sample Solution: Calling the <T>printlnMatches method
Step 1 of 26: PrintlnMatchesExample.java:14
 1package cs1302.lambda;
 2
 3import java.util.function.Predicate;
 4
 5/** Demonstrates passing a predicate to a generic array-processing method. */
 6public class PrintlnMatchesExample {
 7
 8    /**
 9     * Prints the strings containing the letter a.
10     *
11     * @param args the command-line arguments
12     */
13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
24
25} // PrintlnMatchesExample
 1package cs1302.lambda;
 2
 3import java.util.Comparator;
 4import java.util.function.Predicate;
 5
 6/** Select array elements using supplied comparators and predicates. */
 7public class Driver {
 8
 9    /**
10     * Return with a reference to the first greatest element under the comparator.
11     * @param <T> the array element type
12     * @param items a nonempty array of non-null elements
13     * @param comp the comparator defining the ordering
14     * @return a reference to the first greatest element under the comparator
15     */
16    public static <T> T max(T[] items, Comparator<T> comp) {
17        T maxItem = items[0];
18        for (int i = 1; i < items.length; i++) {
19            T item = items[i];
20            int result = comp.compare(item, maxItem);
21            if (result > 0) {
22                maxItem = item;
23            } // if
24        } // for
25        return maxItem;
26    } // max
27
28    /**
29     * Prints the array elements that pass the predicate's test, one per line.
30     *
31     * @param <T> the array element type
32     * @param items the specified array
33     * @param condition the specified predicate
34     */
35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
43
44} // Driver
13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 14

Memory state at the breakpoint on line 14 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 18

Memory state at the breakpoint on line 18 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 22

Memory state at the breakpoint on line 22 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 36

Memory state at the breakpoint on line 36 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 37

Memory state at the breakpoint on line 37 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 38

Memory state at the breakpoint on line 38 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 19

Memory state at the breakpoint on line 19 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 37

Memory state at the breakpoint on line 37 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 38

Memory state at the breakpoint on line 38 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 19

Memory state at the breakpoint on line 19 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 37

Memory state at the breakpoint on line 37 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 38

Memory state at the breakpoint on line 38 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 19

Memory state at the breakpoint on line 19 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 37

Memory state at the breakpoint on line 37 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 38

Memory state at the breakpoint on line 38 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 19

Memory state at the breakpoint on line 19 in PrintlnMatchesExample.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 39

Memory state at the breakpoint on line 39 in Driver.java. [code listing] [download] [open]

> (no output yet)

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 37

Memory state at the breakpoint on line 37 in Driver.java. [code listing] [download] [open]

an

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 38

Memory state at the breakpoint on line 38 in Driver.java. [code listing] [download] [open]

an

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 19

Memory state at the breakpoint on line 19 in PrintlnMatchesExample.java. [code listing] [download] [open]

an

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 39

Memory state at the breakpoint on line 39 in Driver.java. [code listing] [download] [open]

an

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 37

Memory state at the breakpoint on line 37 in Driver.java. [code listing] [download] [open]

an
awesome

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 38

Memory state at the breakpoint on line 38 in Driver.java. [code listing] [download] [open]

an
awesome

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 19

Memory state at the breakpoint on line 19 in PrintlnMatchesExample.java. [code listing] [download] [open]

an
awesome

>_ Console Output

35    public static <T> void printlnMatches(T[] items, Predicate<T> condition) {
36        for (int i = 0; i < items.length; i++) {
37            T item = items[i];
38            if (condition.test(item)) {
39                System.out.println(item);
40            } // if
41        } // for
42    } // printlnMatches
Code visualization diagram for cs1302/lambda/Driver.java line 42

Memory state at the breakpoint on line 42 in Driver.java. [code listing] [download] [open]

an
awesome

>_ Console Output

13    public static void main(String[] args) {
14        String[] myStrings = new String[] {
15            "CSCI", "1302", "is", "an", "awesome", "course!"
16        };
17
18        Predicate<String> containsA = (String t) -> {
19            return t.contains("a");
20        };
21
22        Driver.<String>printlnMatches(myStrings, containsA);
23    } // main
Code visualization diagram for cs1302/lambda/PrintlnMatchesExample.java line 23

Memory state at the breakpoint on line 23 in PrintlnMatchesExample.java. [code listing] [download] [open]

an
awesome

>_ Console Output

Part 3: Hands-on Activity
Download starter code

Download the starter code for this chapter and places it into a subdirectory called cs1302-gen-methods:

bundle1302 gen-methods
- downloading cs1302-gen-methods bundle...
- verifying integrity of downloaded files using sha256sum...
- extracting downloaded archive...
- removing intermediate files...
subdirectory cs1302-gen-methods successfully created
Activity: Fill in the blank: <T>print

Finish the code below so that the print method functions according to the specification:

/**
 * Prints all of the provided list. Each element will be printed
 * on its own line.
 *
 * @param <T> the type of the list elements
 * @param list the specified list
 */
public static <T> void print(List<T> list) {
    for (_____ elem: list) {              // Blank 1
        System.out.println(_________);    // Blank 2
    } // for
} // print
Sample Solution: <T>print
1public static <T> void print(List<T> list) {
2    for (T elem: list) {              // Blank 1
3        System.out.println(elem);     // Blank 2
4    } // for
5} // print
Activity: Fill in the blanks: <T>printlnMatches

Finish the code below so that print functions according to the specifications:

 1/**
 2 * Prints the elements of the list that pass the test specified by the given
 3 * predicate. Each element will be printed on its own line.
 4 *
 5 * @param <T> the type of the list elements
 6 * @param list the specified list
 7 * @param condition the specified predicate
 8 */
 9 public static <T> void printlnMatches(List<T> list, Predicate<T> condition) {
10     for (_____ elem: list) {               // Blank 1
11         if (_______________) {             // Blank 2
12             System.out.println(______);    // Blank 3
13         } // if
14     } // for
15 } // printlnMatches
Sample Solution: <T>printlnMatches
 1/**
 2 * Prints the elements of the list that pass the test specified by the given
 3 * predicate. Each element will be printed on its own line.
 4 *
 5 * @param <T> the type of the list elements
 6 * @param list the specified list
 7 * @param condition the specified predicate
 8 */
 9 public static <T> void printlnMatches(List<T> list, Predicate<T> condition) {
10     for (T elem: list) {
11         if (condition.test(elem)) {
12             System.out.println(elem);
13         } // if
14     } // for
15 } // printMatches
Calling <T>printlnMatches

Use the method printlnMatches to print the names of all movies made after 1999.

Note

You may need to review the Movie class given as part of the Jar file for Project 3.

public static <T> void printlnMatches(List<T> list, Predicate<T> condition) {
    for (T elem: list) {
        if (condition.test(elem)) {
            System.out.println(elem);
        } // if
    } // for
} // printlnMatches
Movie[] movies = ...;

// setup a predicate (an object containing a test method)

// call printlnMatches
Movie[] movies = ...;

Predicate<Movie> after1999 = ____;

Driver.<Movie>printlnMatches(____, ____);
Movie[] movies = ...;

Predicate<Movie> after1999 = (Movie t) -> {
    Year year1999 = Year.of(1999);
    return t.year().after(year1999);
};

Driver.<Movie>printlnMatches(____, ____);
Movie[] movies = ...;

Predicate<Movie> after1999 = (Movie t) -> {
    Year year1999 = Year.of(1999);
    return t.year().after(year1999);
};

Driver.<Movie>printlnMatches(movies, after1999);
Code Update

Update the code in ModelTests to print all movies made after 1999.

Run the code. Looks a bit messy. Let's update the query.

Discussion: Updated Query - Part 1

What if we only want to print the name of all of our movies?

We already have a print method. Can we adjust it to print only the name out of each movie?

public static <T> void print(List<T> list) {
    for (T elem: list) {
        System.out.println(elem + "\n");
    } // for
} // print
Discussion: Updated Query

What if we want to print just the name of the movies made after 1999 (or the name of their director, for example) instead of calling the toString method to print all of the information for the movies?

Need a new method with another functional interface. We will call it printlnMappedMatches.

Discussion: The <T>printlnMappedMatches method

To get started: search for "Java Function" to pull up the Java API page for java.util.function.Function<T, R>…

/**
 * Prints the elements of the array that pas the test
 * specified by the given predicate using a string
 * mapper. Each string-mapped element will be printed on
 * its own line.
 *
 * @param <T> the type of the list elements
 * @param list the specified list
 * @param condition the specified predicate
 * @param mapper the specified string mapper
 */
public static <T> void printlnMappedMatches(
    List<T> list, Predicate<T> condition, Function<T, String> mapper
) {
    throw new UnsupportedOperationException("not yet implemented");
} // printlnMappedMatches

Suppose we want to implement the printlnMappedMatches method above.

  • Is the method printlnMappedMatches a generic method? How can you tell?

  • What do you think is the purpose of mapper?

  • What method can we call using mapper as the calling object?

Solution
  • Yes. It has a generic type parameter T.

  • It changes the data type of an element. In this case, it changes the type from T to String. That will be perfect for converting a Movie to its name (String).

  • The single, abstract method in Function is apply.

Activity: Writing the <T>printlnMappedMatches method
/**
 * Prints the elements of the array that pass the test
 * specified by the given predicate using a string
 * mapper. Each string-mapped element will be printed on
 * its own line.
 *
 * @param <T> the type of the list elements
 * @param list the specified list
 * @param condition the specified predicate
 * @param mapper the specified string mapper
 */
public static <T> void printlnMappedMatches(
    List<T> list, Predicate<T> condition, Function<T, String> mapper
) {
    throw new UnsupportedOperationException("not yet implemented");
} // printlnMappedMatches

Write the code for the printlnMappedMatches method on your exit ticket (and in your own notes). Be sure to include the method signature. Do not include a Javadoc comment, unless you need it for your notes.

Sample Solution: Writing the <T>printlnMappedMatches method
public static <T> void printlnMappedMatches(
    List<T> list, Predicate<T> condition, Function<T, String> mapper
) {
    for (int i = 0; i < list.size(); i++) {
        T item = list.get(i);
        if (condition.test(item)) {
            String mappedItem = mapper.apply(item);
            System.out.println(mappedItem);
        } // if
    } // for
} // printlnMappedMatches
Activity: Calling the <T>printlnMappedMatches method
public static <T> void printlnMappedMatches(
    List<T> list, Predicate<T> condition, Function<T, String> mapper
) { ...

Use the method printlnMappedMatches to print the names of all movies made after 1999.

List<Movie> movies = ...;

// setup a predicate

// setup a mapper function

// call printlnMappedMatches
List<Movie> movies = ...;

Predicate<Movie> after1999 = ____;

Function<Movie, String> asTitle = ____;

Driver.<Movie>printlnMappedMatches(____, ____, ____);
List<Movie> movies = ...;

Predicate<Movie> after1999 = (Movie t) -> {
    Year year1999 = Year.of(1999);
    return t.year().after(year1999);
};

Function<Movie, String> asTitle = ____;

Driver.<Movie>printlnMappedMatches(____, ____, ____);
List<Movie> movies = ...;

Predicate<Movie> after1999 = (Movie t) -> {
    Year year1999 = Year.of(1999);
    return t.year().after(year1999);
};

Function<Movie, String> asTitle = (Movie t) -> {
    return t.title();
};

Driver.<Movie>printlnMappedMatches(____, ____, ____);
List<Movie> movies = ...;

Predicate<Movie> after1999 = (Movie t) -> {
    Year year1999 = Year.of(1999);
    return t.year().after(year1999);
};

Function<Movie, String> asTitle = (Movie t) -> {
    return t.title();
};

Driver.<Movie>printlnMappedMatches(movies, after1999, asTitle);