有一个列表,我想创建books对象并将所有book对象添加到此List中。在这里我用像这样的普通方法做。

public static List<Books> listOfBooks = new ArrayList<>();
public static void addProduct() {
        Books book1 = new Books("java", "games", 200.56);
        Books book2 = new Books("c", "dennis", 300.56);
        Books book3 = new Books("c++", "Bjarne", 250.56);
        Books book4 = new Books("javaScript", "Brendan", 209.56);
        Books book5 = new Books("Sql", "Donald", 249.56);
        listOfBooks.add(book1);
        listOfBooks.add(book2);
        listOfBooks.add(book3);
        listOfBooks.add(book4);
        listOfBooks.add(book5);
    }


我想要使​​用lamda表达式进行相同的操作,但我不知道该怎么做。请帮帮我吗?

最佳答案

您可以这样写:

Arrays.asList(book1, book2, ...).forEach(b -> listOfBooks.add(b));


或者使用方法引用而不是lambda来缩短:

Arrays.asList(book1, book2, ...).forEach(listOfBooks::add);


但这并不比编写真正好:

listOfBooks.addAll(Arrays.asList(book1, book2, ...));

10-07 15:35