![](/img/trans.png)
[英]How do I iterate over elements of an array in Java while I am inside of a for loop to iterate over the elements of an array?
[英]How to iterate over Array List and modify elements inside the object in Java?
我有一個數組列表List<CatchItem.CatchesItem> catchesItems = new ArrayList<>()
; 包含以下對象:
[
{"amount":1,"condition":0.0,"time":"Feb 17, 2021 05:10:42 PM"},
{"amount":4,"condition":1.0,"time":"Feb 17, 2021 05:10:48 PM"},
{"amount":5,"condition":2.0,"time":"Feb 18, 2021 05:10:54 PM"}
]
要迭代列表,我可以通過以下方式:
for (int i = 0; i < catchesItems.size(); i++) {
catchesItems.get(i);
}
但是,我如何檢查列表中的 object 是否包含今天的時間戳,如果它包含然后通過附加新值來修改 object 中的金額元素,如果沒有,則保持原樣?
假設 class CatchesItem
具有定義為LocalDateTime
的time
字段,則對今天的時間戳的檢查可以實現如下:
import java.time.*;
// ...
LocalDate today = LocalDate.now();
for (CatchesItem item : items) {
if (today.equals(item.getTime().toLocalDate())) {
item.setAmount(item.getAmount() + 5); // add some value to amount
}
}
items.forEach(System.out::println);
Output(截至 2 月 18 日的輸入數據)
CatchesItem(amount=1, condition=0.0, time=2021-02-17T17:10:42)
CatchesItem(amount=4, condition=1.0, time=2021-02-17T17:10:48)
CatchesItem(amount=10, condition=2.0, time=2021-02-18T17:10:54)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.