Bài 314: Ví dụ biểu thức Lambda với Filter Collection Data

Ngày đăng: 1/7/2023 10:17:47 AM

Dưới đây là ví dụ biểu thức Lambda với Filter Collection Data.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38     

39

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

Nguồn tin: viettuts.vn