GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing zetcode.com — Java Lambda Expressions - Mastering Lambda Expressions in Java Java Lambda ExpressionsLast modified October 13, 2026 Lambda expressions, introduced in Java 8, bring functional programming to Java. A lambda expression is an anonymous function: it has parameters and a body, but no name, and it provides an inline implementation of a functional interface. This tutorial covers the syntax, the most common functional interfaces, and practical use with arrays, collections, and streams. The basic syntax of a lambda expression is as follows: (parameters) -> expression
(parameters) -> { statements; }
The syntax can be abbreviated in several ways:
Sorting an ArraySorting arrays is a common task in programming, and lambda expressions make it easier by providing a concise way to define comparison logic. The following example demonstrates sorting an array of strings alphabetically using a lambda expression. com/zetcode/LambdaSortEx.java
package com.zetcode;
import java.util.Arrays;
public class LambdaSortEx {
public static void main(String[] args) {
String[] words = { "kind", "massive", "atom", "car", "blue" };
Arrays.sort(words, (s1, s2) -> s1.compareTo(s2));
System.out.println(Arrays.toString(words));
}
}
This example demonstrates sorting an array of strings using the
$ java com/zetcode/LambdaSortEx.java [atom, blue, car, kind, massive] Functional Interfaces and Lambda Expressions
Functional interfaces, which contain a single abstract method, are the
foundation for lambda expressions in Java. Lambda expressions provide a compact
way to implement these interfaces. The optional Implementing a Greeting ServiceCreating custom functional interfaces allows developers to define specific behaviors. This example shows how to use a lambda expression to implement a simple greeting service that outputs messages to the console. com/zetcode/LambdaGreetingEx.java
package com.zetcode;
@FunctionalInterface
interface GreetingService {
void greet(String message);
}
public class LambdaGreetingEx {
public static void main(String[] args) {
GreetingService gs = msg -> System.out.println(msg);
gs.greet("Good night");
gs.greet("Hello there");
}
}
In this example, a $ java com/zetcode/LambdaGreetingEx.java Good night Hello there Common Functional Interfaces
The Using the Function Interface
The com/zetcode/LambdaFunctionEx.java
package com.zetcode;
import java.util.function.Function;
public class LambdaFunctionEx {
public static void main(String[] args) {
Function<Integer, Integer> square = x -> x * x;
System.out.println(square.apply(5));
}
}
This example uses the $ java com/zetcode/LambdaFunctionEx.java 25 Filtering Data with StreamsJava streams, combined with lambda expressions, provide a powerful way to process collections of data. This example demonstrates filtering a list of objects based on a condition defined by a lambda expression. com/zetcode/LambdaFilterEx.java
package com.zetcode;
import java.util.List;
public class LambdaFilterEx {
public static void main(String[] args) {
List<User> persons = List.of(
new User("Jack", "[email protected]"),
new User("Peter", "[email protected]"),
new User("Lucy", "[email protected]"),
new User("Robert", "[email protected]"),
new User("Martin", "[email protected]")
);
List<User> result = persons.stream()
.filter(person -> person.email().endsWith("@post.com"))
.toList();
result.forEach(p -> System.out.println(p.name()));
}
}
record User(String name, String email) {}
This example uses a lambda expression within a stream to filter
$ java com/zetcode/LambdaFilterEx.java Peter Robert Mapping Data with Streams
The com/zetcode/LambdaMapEx.java
package com.zetcode;
import java.util.List;
public class LambdaMapEx {
public static void main(String[] args) {
List<String> words = List.of("apple", "banana", "cherry");
List<Integer> lengths = words.stream()
.map(word -> word.length())
.toList();
System.out.println(lengths);
}
}
This example demonstrates the use of a lambda expression with the
$ java com/zetcode/LambdaMapEx.java [5, 6, 6] Using Consumer Interface
The com/zetcode/LambdaConsumerEx.java
package com.zetcode;
import java.util.function.Consumer;
public class LambdaConsumerEx {
public static void main(String[] args) {
Consumer<String> printUpperCase = text -> System.out.println(text.toUpperCase());
printUpperCase.accept("hello");
printUpperCase.accept("java lambda");
}
}
This example uses the $ java com/zetcode/LambdaConsumerEx.java HELLO JAVA LAMBDA Using Supplier Interface
The com/zetcode/LambdaSupplierEx.java
package com.zetcode;
import java.util.function.Supplier;
public class LambdaSupplierEx {
public static void main(String[] args) {
Supplier<String> randomGreeting = () -> {
String[] greetings = {"Hello", "Hi", "Greetings"};
return greetings[(int) (Math.random() * greetings.length)];
};
System.out.println(randomGreeting.get());
System.out.println(randomGreeting.get());
}
}
This example uses the $ java com/zetcode/LambdaSupplierEx.java Hi Greetings Combining Predicates
The com/zetcode/LambdaPredicateEx.java
package com.zetcode;
import java.util.List;
import java.util.function.Predicate;
public class LambdaPredicateEx {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8);
Predicate<Integer> isEven = n -> n % 2 == 0;
Predicate<Integer> isGreaterThanFour = n -> n > 4;
List<Integer> result = numbers.stream()
.filter(isEven.and(isGreaterThanFour))
.toList();
System.out.println(result);
}
}
This example combines two $ java com/zetcode/LambdaPredicateEx.java [6, 8] Capturing Variables
A lambda expression can use local variables from its enclosing scope, but only
if they are final or effectively final, meaning they are never
reassigned after initialization. Unlike an anonymous class, a lambda does not
introduce a new scope: com/zetcode/LambdaCaptureEx.java
package com.zetcode;
import java.util.List;
public class LambdaCaptureEx {
public static void main(String[] args) {
String prefix = "Hello, ";
List<String> names = List.of("Jack", "Lucy", "Peter");
names.forEach(name -> System.out.println(prefix + name));
}
}
The lambda captures the $ java com/zetcode/LambdaCaptureEx.java Hello, Jack Hello, Lucy Hello, Peter Method References
When a lambda only calls an existing method, a method reference is a shorter
alternative. The com/zetcode/MethodRefEx.java
package com.zetcode;
import java.util.List;
public class MethodRefEx {
public static void main(String[] args) {
List<String> words = List.of("kind", "massive", "atom", "car", "blue");
words.stream()
.map(String::toUpperCase)
.sorted(String::compareTo)
.forEach(System.out::println);
}
}
The example converts the words to uppercase, sorts them, and prints each one. $ java com/zetcode/MethodRefEx.java ATOM BLUE CAR KIND MASSIVE Summary
Lambda expressions provide concise implementations of functional interfaces.
Combined with the built-in interfaces in SourceJava Lambda Expressions Documentation AuthorMy name is Jan Bodnar, a dedicated programmer with extensive experience in software development. Since 2007, I have authored over 1,400 programming articles and eight e-books. With more than a decade of teaching experience, I am committed to sharing knowledge and fostering a deeper understanding of programming concepts. List all Java tutorials. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |