java - 更新对象列表中对象的值
问题描述
我必须更新对象列表中的对象字段
我有一堂“书”
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 的解决方案,那就太好了
解决方案
您可以在流列表上使用过滤器,然后简单地更新计数
public void updateCount(String bookName, int updateBy) {
books.stream().filter(book -> book.getName().equals(bookName)).forEach(
book -> book.setCount(book.getCount() + updateBy)
);
}
推荐阅读
- jquery - Jquery - 关闭后一周不显示 div(弹出窗口)
- javascript - NodeJS 一个函数返回一个未定义的。
- server - 有关端口的详细信息(例如在 xammp 端口 80 中)这些端口是什么?
- java - 使用 JNI 从 java 调用 fortran dll
- spring - 从 Spring OAuth2 YML 中提取常用值
- python - 熊猫分组和求和/存储
- c# - 手动设置组合框项时如何使用 mvvm 中的绑定在 wpf 中设置组合框默认值
- asp.net-web-api - WebAPI 文件上传 MultipartFormDataStreamProvider 清理访问被拒绝
- python - 时间序列数据的 CV 拆分
- html - 相同长度字符的像素差异