'loop through a list of objects with utc and remove the object with oldest utc java
I have a list like below
"pList": [
{
"Utc": "2021-12-20T05:10:20+0000",
"key": {
"num": "23131"
}
},
{
"Utc": "2021-12-20T05:15:20+0000",
"key": {
"num": "23131"
}
},
{
"Utc": "2021-12-20T05:20:20+0000",
"key": {
"num": "23131"
}
}
]
now , i need to loop through this list and delete the oldest utc. How do i achieve this in java ? (List should contain 2 items at given instance. I need to look for the oldest utc item and remove it from the list)
This is what i have tried
if(pList.size() > 2) {
for(int i = 1; i < pList.size() ; i++ ) {
Instant prior = pList.get( i - 1 ).Utc();
Instant current = pList.get( i ).Utc();
if(prior.isBefore(current)) {
pList.remove(i);
}
}
}
Solution 1:[1]
Here's how i implemented it,
if(pList.size() > 2) {
for(int i = 1; i < pList.size() ; i++ ) {
Instant prior = pList.get( i - 1 ).getUtc();
Instant current = pList.get( i ).getUtc();
if(prior.isBefore(current)) {
pList.remove(i-1);
}
}
}
It made sure that pList has only 2 items at given instance and removed the oldest if there's a new item coming into the list.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aki |
