当前位置:网站首页>Lambda intermediate operation flatmap

Lambda intermediate operation flatmap

2022-06-12 00:43:00 Leon_ Jinhai_ Sun

flatMap

​ map Only one object can be converted into another object as an element in the stream . and flatMap You can convert an object into multiple objects as elements in the stream .

Patients with a :

​ Print the names of all books . Require duplicate elements to be de duplicated .

//         Print the names of all books . Require duplicate elements to be de duplicated .
        List<Author> authors = getAuthors();

        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .forEach(book -> System.out.println(book.getName()));

Example 2 :

​ Print all categories of existing data . De duplication of classification is required . This format cannot appear : philosophy , love

//         Print all categories of existing data . De duplication of classification is required . This format cannot appear : philosophy , love       love 
        List<Author> authors = getAuthors();
        authors.stream()
                .flatMap(author -> author.getBooks().stream())
                .distinct()
                .flatMap(book -> Arrays.stream(book.getCategory().split(",")))
                .distinct()
                .forEach(category-> System.out.println(category));

原网站

版权声明
本文为[Leon_ Jinhai_ Sun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206120036470242.html