Dưới đây là ví dụ biểu thức Lambda với Filter Collection Data.
package vn.viettuts.java8;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
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 class LambdaExpressionExample11 {
public static void main(String[] args) {
List<Product> list = new ArrayList<Product>();
list.add(new Product(1, "Samsung A8", 17000f));
list.add(new Product(3, "Iphone 8X", 65000f));
list.add(new Product(2, "Sony Xperia X8", 25000f));
list.add(new Product(4, "Nokia L7", 15000f));
list.add(new Product(5, "Redmi Note 7", 26000f));
list.add(new Product(6, "Lenevo Vibe", 19000f));
// sử dụng biểu thức lambda để filter data
Stream<Product> filtered_data = list.stream()
.filter(p -> p.price > 20000);
// sử dụng lambda duyệt các phần tử của collection
filtered_data.forEach(product -> {
System.out.println(product.name + ": " + product.price);
});
}
}
Kết quả:
Iphone 8X: 65000.0 Sony Xperia X8: 25000.0 Redmi Note 7: 26000.0