# Lambda expressions exercises and practice

While lambda expressions in java 8 are really cool in action, the school curriculum offers no exercises in this. So essentially, students never actually learn how to use lambda expressions and the java 8 functional interfaces that go with it when teaching in java (i.e. Stream, Predicate etc.)

There are a few periods for labs and practice which can be devoted for lambda expressions, but I am not sure what kind of labs I can make, which are focused on lambda expressions (not only utilizing them).

What I did think of is asking them to perform a number of tasks:

1. given a List of String and some condition (not coded as a Predicate, yet...), return a List of all strings that meet the condition. This exercise is meant as a starter. Just to get them going.
2. Here the fun starts Streaming. They are given a list of objects (which I wrote) that each have a String and an Integer. They need to return a list of the integers from those objects.

The problem is that those two are very short, and are introductory. I am trying to think of other exercises or tasks which are almost entirely with lambda expressions.

Which kind of exercises could I give the students that would both show them just how cool lambda expressions and the functional API are, but also give them plenty of hands-on experience with what Java's functional API has to offer?

(PS, the students are high school students)

• Lambda expressions is a big topic and many features were added that interact with each other (functional interfaces, for example) Are you focused on just the narrow question, as stated, or the whole shebang? Your samples are from a pretty narrow subset - lisp-like lists. – Buffy Jul 3 '17 at 12:50
• @Buffy whoops. I forgot to mention that it's high school level. And I am mainly looking to give them hands on experience with functional interfaces already in java. Does my edit answer your question? – ItamarG3 Jul 3 '17 at 12:53

One idea might be to borrow SQL-related exercises -- find problems asking the reader to come up with some sort of SQL query to find information, and rephrase the problem and ask students to come up with an equivalent query using only Java's functional interface and lambda expressions. (I wouldn't bother telling students these questions were originally about SQL).

Translating basic SELECT queries would be pretty straightforward, I imagine -- implementing things like JOIN or GROUPBY would be a little trickier, I imagine. (You can do join by doing something like seq1.stream().flatMap(a -> seq2.stream().filter(b -> a.id == b.id).map(b -> combine(a, b)) and group-by using Collectors.groupingBy. The API isn't as elegant as it could be here, but I suppose that's Java for you.).

You can make it even trickier by asking them to translate the equivalent of nested queries or asking them to extract information from multiple lists at once (e.g. multiple 'tables'), instead of just one.

Stepping away from data manipulation, something else you could do is to introduce students to GUI frameworks or webserver backends or anything else that's event-driven -- event handlers are one example of a place where lambdas and method references shine.

My last idea is a bit of a stretch, but you could perhaps ask students to invent (or use) a mini-DSL involving lambda expressions in some way. This would be a bit more involved -- the exercise would be less about using Java's already existing interface, and more about writing their own. (It's a shame that Java doesn't have anything like C#'s extension methods, otherwise this would be much easier since you can trivially augment the existing API, which can be pretty handy).

If you need ideas for DSLs, you can maybe take inspiration from functional languages like Haskell and how they use higher-level constructs like monads and functors to build quite interesting abstractions and simplify things like error handling. I wouldn't use the word "monad" or "functor" at any point though, and you'll probably need to be careful to avoid accidentally making your exercise more about manipulating generics instead of lambdas.

• like LINQ? I like the idea, – ItamarG3 Jul 3 '17 at 18:07
• @ItamarG3 -- I'm a big fan of LINQ, yeah, though I admit I wasn't thinking about it at first when I came up with the SQL exercises idea. – Michael0x2a Jul 3 '17 at 18:30
• What I wouldn't do to change the school curriculum to C#... – ItamarG3 Jul 3 '17 at 18:44
• Creating a Domain Specific Language is one of my favorite solutions to some types of problems. – user737 Jul 13 '17 at 19:44

One of the interesting things added to java in v8 is functional interfaces. Previously java only matched things up and verified correctness by type (type names). With functional interfaces, java now looks at the structure of code in certain situations.

One interesting feature you can add is a method to do simple repetition. I like to teach a lot of things before if and while, but sometimes you just need repetition and the most common sort is a constant-number-of-iterations loop.

@FunctionalInterface
public interface LocalCommand
{
public void accept();

}

/**
*  Repeat a method a given number of times
* @param howMany number of times to repeat the method
* @param what the method itself, as a Command. Especially useful in Java 8
*/
public static void repeat(int howMany, LocalCommand what){
for (int i = 0; i < howMany; ++i){
what.accept();
}
}


Usage:

public void aCommand(){
// do something interesting
}

repeat(3, aCommand()); // structural matching with the functional interface
repeat(3, () -> {aCommand();}); //lambda expression
repeat(3, () -> {System.out.println("Hello");}); //lambda expression


In java 8 you don't need to ever explicitly say that aCommand is, in fact, aCommand and you don't need a new enclosing type to implement the functional interface. You don't even need to specifically say that it is a functional interface, Java will grok it by structure alone.

With repeat(...) in my library I can do repetition before I need to talk about for and while loops.

I used only the simplest case of a functional interface here. You can use Consumers, etc just as well with only a bit more complexity.

I think the most critical thing about lambda functions is that they enable the convenient use of map and filter functions on collections and streams. Exercises in using these (and their equivalents in Optional, which is perhaps just as important, allowing us to get rid of null as it does) are probably the best way of showing what you can achieve with lambda functions.

• Welcome to CS Educators Stack Exchange! I hope we see more answers and questions from you. – Ellen Spertus Jul 15 '17 at 18:11

A second example of fairly simple lambda expressions that lets you delve into some interesting side discussions is the problem of reversing a linked list in linear time.

It is easy to use list 'head', 'tail', and 'cons' to write a method, putlast, that puts the head of a list at its tail, removing it from the head, but otherwise leaving the elements intact. This function runs in linear time on a linked list.

It is easy to write reverseList using putLast, but it is quadratic in time and a discussion is useful to students if you are doing this sort of thing at all.

It is a bit more challenging to write a linear-time reverseList. The technique is very cool and teaches a lot about functional programming, not using intermediate variables to hold things. I won't give away the secret here as it is a mind expander to discover it.

• A simple example is adding a listener to, for example, a Button. It is a bit cleaner then anonymous inner classes and doesn't break the mental flow quite as much. The method needs no name and isn't referred to in any case from user code. Therefore, a good match of technique to need. – Buffy Jul 13 '17 at 18:46