java · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a method you can pass around.
Some methods want behaviour as well as data. list.removeIf needs to know which items to remove. A lambda is that behaviour written as a value: price -> price > 50. It has no name and no return type, because Java works those out from where you use it.
Parameters go left of the , the body goes right. One parameter needs no brackets; none or two do: () -> 42, (a, b) -> a + b. A one-expression body hands back its value. A longer body uses curly brackets and return.
A lambda can read the variables in the method around it, but only ones: never given a new value after the first. Change one and Java stops you, because the lambda might run later, after the variable has moved on.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> prices = new ArrayList<>(List.of(12, 80, 45, 120, 9));
int limit = 50;
prices.removeIf(price -> price > limit);
prices.sort((a, b) -> b - a);
prices.forEach(price -> System.out.println("Under budget: " + price));
}
} A comparator lambda answers like compareTo, so (a, b) -> b - a puts the biggest first.
guess first
Which songs survive? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> songs = new ArrayList<>(List.of("Yellow", "Hello", "Halo", "Help!"));
songs.removeIf(song -> song.startsWith("H"));
songs.add("Hey Jude");
System.out.println(songs);
}
}
your turn
Your turn. Clean up a mailing list.
On line 6, write a lambda that answers true for addresses without an @, so removeIf drops them. email.contains("@") checks for one.
output
press run to see what happens
fix it
The basket total will not compile. Can you fix it?
output
press run to see what happens
- Java says variables used in a lambda must be effectively final. Which variable changes?
totalgets a new value inside the lambda on line 6. A lambda may read it, never change it.- Swap line 6 for a for-each loop:
for (int price : basket) { total = total + price; }, then run.
nailed it
you can hand behaviour to other code. :D
- A lambda is behaviour written as a value:
x -> x * 2. - Parameters go left of the arrow, the body goes right.
- Lambdas may read nearby variables, never change them.
new words in your collection
- lambda
- arrow
- effectively final
This lesson isn’t saved. A free account remembers every lesson you finish.