首页 > 解决方案 > 更新对象列表中对象的值

问题描述

我必须更新对象列表中的对象字段

我有一堂“书”

class Book{
   String name ;
   int count;
  ....constructor
  .. getter setters
}

现在我有一个方法 updateCount

public void updateCount() {
  List<Book> books = new ArrayList<Book>() {
   {
     add(new Book("Book1", 1));
     add(new Book("Book2" , 2));

     // it can be more than 2 and in any manner not in any defined sequence  but we can
     // identify with the book name
   }
}

public static void main(String[] args) {
   /// now i have to update the value of count to 3 in book2
   /// how can I update
}

如果有人有使用 java 8 的解决方案,那就太好了

标签: javajava-8

解决方案


您可以在流列表上使用过滤器,然后简单地更新计数

public void updateCount(String bookName, int updateBy) {
  books.stream().filter(book -> book.getName().equals(bookName)).forEach(
      book -> book.setCount(book.getCount() + updateBy)
  );
}

推荐阅读