Higher Order Functions

mixer

The Comparator Interface

Comparator with Lambda Expressions

Your Turn

Complete this program to sort an array of strings by decreasing length.

Comparator.comparing

Your Turn

Complete this program to sort a collection of countries by population and by population density (people per square kilometer).

Use Comparator.comparing(...).

What Does Comparator.comparing Do?

Your Turn

Complete this program to provide a higher order function Comparators.reverse that reverses a comparator. For example, if comp sorts strings by increasing length, then Comparators.reverse(comp) should sort by decreasing length.

Higher-Order Functions

Higher-Order Functions 2

Your Turn

Complete this program to provide a higher order function Words.longerThan that yields a predicate testing whether a string has length > n.

Note the nifty methods and and negate of the Predicate interface. In Java 8, it is legal to have “default” methods in an interface. Check out their implementations here.

Method Expressions

Constructor Expressions

Method Expressions and Comparators

Exercises

  1. Complete this program to sort the list of words first by the number of vowels, then in alphabetical order. Use Comparator.comparing and two method expressions.

  2. The Collection<T> interface has two toArray methods:

    Object[] 	toArray()
    <T> T[] 	toArray(T[] a)

    The first one returns an array of type Object, which is unsatisfactory. The second one requires the caller to provide an array and uses reflection to grow it if it was too short. Until the invention of constructor expressions, there was no better way.

    In this program, there is a method that allows you to pass a constructor expression. Call that method to turn a List<String> into a String[].

  3. In this program, reimplement filter so that it works with arrays.