chand mohd
chand mohd

Reputation: 2550

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?

Upvotes: 0

Views: 1004

Answers (2)

Flown
Flown

Reputation: 11740

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

Upvotes: 0

janos
janos

Reputation: 124646

You could write:

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

Or shorter using a method reference instead of a lambda:

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

But that's not really better than writing:

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

Upvotes: 1

Related Questions