Lamda表达式将对象添加到列表中

时间:2017-11-02 06:42:59

标签: java collections

有一个List,我想创建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表达式进行相同的操作,但我不知道该怎么做。请帮帮我吗?

2 个答案:

答案 0 :(得分:1)

可以写:

List<String> mylist = new Arraylist<>(Collections.nCopies("4.5",count));

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

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

但这并不比写作好:

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

答案 1 :(得分:0)

Stream API正在使用lambda表达式,但不属于它。

public static List<Books> listOfBooks = new ArrayList<>();
public static void addProduct() {
  String[] languages = {"java", "c", "c++", "javascript", "Sql"};
  String[] authors = {"games", "dennis", "Bjarne", "Brendan", "Donald"};
  double[] prices = {200.56d, 300.56d, 250.56d, 209.56d, 249.56d};
  listOfBooks = IntStream.range(0, languages.length)
                        .mapToObj(i -> new Books(languages[i], authors[i], prices[i]))
                        .collect(Collectors.toList());
  // Alternatively:
  /* IntStream.range(0, languages.length)
          .mapToObj(i -> new Books(languages[i], authors[i], prices[i]))
          .forEach(listOfBooks::add);
  */
}