Answers.Body: <p>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. </p>
  
  <p>I can add examples to this answer to clarify if anyone asks. </p>
  
  <p>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. </p>
  
  <pre><code>@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 &lt; howMany; ++i){
          what.accept();
      } 
  }
  </code></pre>
  
  <p>Usage:</p>
  
  <pre><code>public void aCommand(){
      // do something interesting
  }
  
  repeat(3, aCommand()); // structural matching with the functional interface
  repeat(3, () -&gt; {aCommand();}); //lambda expression   
  repeat(3, () -&gt; {System.out.println("Hello");}); //lambda expression
  </code></pre>
  
  <p>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. </p>
  
  <p>With repeat(...) in my library I can do repetition before I need to talk about <code>for</code> and <code>while</code> loops.</p>
  
  <hr>
  
  <p>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. </p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-01-23T16:05:40.573Z
Answers.Text: To simplify the library code provided to students (and give the inquisitive students who poke around the library code some exposure to a useful standard library class), you could use `Runnable` here instead of defining a new interface.
Answers.UserDisplayName: kaya3
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-03T13:16:05.327Z
Answers.LastActivityDate: 2017-07-03T13:39:45.187Z
Answers.LastEditDate: 2017-07-03T13:39:45.187Z
Answers.UserDisplayName: Buffy
Answers.Body: <p>I think the most critical thing about lambda functions is that they enable the convenient use of <code>map</code> and <code>filter</code> functions on collections and streams. Exercises in using these (and their equivalents in <code>Optional</code>, which is perhaps just as important, allowing us to get rid of <code>null</code> as it does) are probably the best way of showing what you can achieve with lambda functions.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T18:11:16.623Z
Answers.Text: Welcome to CS Educators Stack Exchange! I hope we see more answers and questions from you.
Answers.UserDisplayName: Ellen Spertus
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-15T17:52:15.433Z
Answers.LastActivityDate: 2017-07-15T17:52:15.433Z
Answers.UserDisplayName: Jules
Answers.Body: <p>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. </p>
  
  <p>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. </p>
  
  <p>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. </p>
  
  <p>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. </p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-13T18:46:49.610Z
Answers.Text: 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.
Answers.UserDisplayName: Buffy
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2020-01-27T06:49:03.433Z
Answers.Text: Actually, lambdas are syntactic sugar + type inference on top of anonymous classes with only one non-default method (functional interfaces)
Answers.UserDisplayName: Michel Billaud
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-03T13:22:37.790Z
Answers.LastActivityDate: 2017-07-03T13:22:37.790Z
Answers.UserDisplayName: Buffy
Answers.Body: <p>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).</p>
  
  <p>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 <code>seq1.stream().flatMap(a -&gt; seq2.stream().filter(b -&gt; a.id == b.id).map(b -&gt; combine(a, b))</code> and group-by using <code>Collectors.groupingBy</code>. The API isn't as elegant as it could be here, but I suppose that's Java for you.). </p>
  
  <p>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.</p>
  
  <p>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 -- <a href="http://code.makery.ch/blog/javafx-8-event-handling-examples/" rel="nofollow noreferrer">event handlers</a> are one example of a place where lambdas and method references shine.</p>
  
  <p>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).</p>
  
  <p>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.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-03T18:07:58.037Z
Answers.Text: like LINQ? I like the idea,
Answers.UserDisplayName: ItamarG3
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-03T18:30:51.830Z
Answers.Text: @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.
Answers.UserDisplayName: Michael0x2a
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-03T18:44:08.933Z
Answers.Text: What I wouldn't do to change the school curriculum to C#...
Answers.UserDisplayName: ItamarG3
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-07-03T17:54:29.170Z
Answers.LastActivityDate: 2017-07-03T18:01:59.343Z
Answers.LastEditDate: 2017-07-03T18:01:59.343Z
Answers.UserDisplayName: Michael0x2a
Body: <p>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 <em>how to use</em> lambda expressions and the java 8 functional interfaces that go with it when teaching in java (i.e. <code>Stream</code>, <code>Predicate</code> etc.)</p>
  
  <p>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 <em>focused</em> on lambda expressions (not only <em>utilizing</em> them).</p>
  
  <p>What I <em>did</em> think of is asking them to perform a number of tasks:</p>
  
  <ol>
  <li>given a <code>List</code> of <code>String</code> and some condition (not coded as a <code>Predicate</code>, yet...), return a <code>List</code> of all strings that meet the condition. This exercise is meant as a starter. Just to get them going.</li>
  <li>Here the fun starts <code>Stream</code>ing. 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. </li>
  </ol>
  
  <p>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. </p>
  
  <p>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?</p>
  
  <p>(PS, the students are high school students)</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-03T12:50:50.797Z
Comments.Text: 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.
Comments.UserDisplayName: Buffy
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-07-03T12:53:07.843Z
Comments.Text: @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?
Comments.UserDisplayName: ItamarG3
Tags: <secondary-education><java><exercises><lambda-expressions>
Title: Lambda expressions exercises and practice
ThreadText: # Lambda expressions exercises and practice
  
  (Asked by: username_0 on 2017-07-03)
  
  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 `Stream`ing. 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)
  
  **Tags:** secondary-education, java, exercises, lambda-expressions
  
  > **Comments:**
  > **username_1**: 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.  
  > **username_0**: @username_1 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?  
  
  ---
  
  ## 4 answers
  
  ### Answer by username_6 on 2017-07-03. Score: 2 | Accepted answer
  
  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](http://code.makery.ch/blog/javafx-8-event-handling-examples/) 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.
  
  > **Comments:**
  > **username_0**: like LINQ? I like the idea,  
  > **username_6**: @username_0 -- 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.  
  > **username_0**: What I wouldn't do to change the school curriculum to C#...  
  
  ---
  
  ### Answer by username_1 on 2017-07-03. Score: 5
  
  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.
  
  I can add examples to this answer to clarify if anyone asks.
  
  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.
  
  > **Comments:**
  > **username_2**: To simplify the library code provided to students (and give the inquisitive students who poke around the library code some exposure to a useful standard library class), you could use `Runnable` here instead of defining a new interface.  
  
  ---
  
  ### Answer by username_3 on 2017-07-15. Score: 2
  
  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.
  
  > **Comments:**
  > **username_4**: Welcome to CS Educators Stack Exchange! I hope we see more answers and questions from you.  
  
  ---
  
  ### Answer by username_1 on 2017-07-03. Score: 1
  
  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.
  
  > **Comments:**
  > **username_1**: 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.  
  > **username_5**: Actually, lambdas are syntactic sugar + type inference on top of anonymous classes with only one non-default method (functional interfaces)  
  
  ---
  
  