Самым плотным образом лямбды связаны со Stream API. Фильтрация, поиск и обработка данных выглядят очень компактно.
Пример: найти продукты с ценой больше 100 и вывести их в консоль в нужном формате.
list.stream().filter(p -> p.price > 1000).forEach(
product -> System.out.println(product.name + ": " + product.price)
);Без лямбд и Stream API код выглядел бы длиннее, хотя новичкам на первых порах он все же кажется проще :)
for (Product product : list) {
if (product.price > 1000) {
System.out.println(product.name + ": " + product.price);
}
}Полный листинг
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Main5 {
static class Product {
int id;
String name;
float price;
public Product(int id, String name, float price) {
super();
this.id = id;
this.name = name;
this.price = price;
}
}
public static void main(String[] args) {
List<Product> list = new ArrayList<Product>();
list.add(new Main5.Product(1, "iPhone 13", 1000));
list.add(new Main5.Product(2, "MacBook 16", 3500));
list.add(new Main5.Product(3, "iMac", 3000));
list.add(new Main5.Product(4, "Samsung note", 800));
list.add(new Main5.Product(4, "Nokia a1", 300));
list.stream().filter(p -> p.price > 1000).forEach(
product -> System.out.println(product.name + ": " + product.price)
);
}
}