Search code examples
javacollections

Lambda expression to add object into list


there is a List and i want to create books object and add all the book object into this List. here I did with normal approach like this .

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);
    }

I want the same operation by using lambda expression but i do not know how to do it. please help me out?


Solution

  • The Stream API is using lambda expression, but are not part of it.

    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);
      */
    }