I have list of objects:
{
"rn": "14",
"time": "2020-06-16 16:47:55",
"id": 42332392988,
"termname": "S1160AFB",
"type": "100",
"trancode": "110",
"pan": "4790729949581839",
"amount": "360.96",
"approvalcode": "44444"
},
{
"rn": "15",
"time": "2020-06-16 16:48:55",
"id": 42330308379,
"termname": "S1160AFB",
"type": "100",
"trancode": "110",
"pan": "4149510064617121",
"amount": "360.96",
"approvalcode": "55555"
},
{
"rn": "13",
"time": "2020-06-16 16:49:11",
"id": 42332530886,
"termname": "S1160AFB",
"type": "420",
"trancode": "110",
"pan": "4790729949581839",
"amount": "360.96",
"approvalcode": "44444"
}
I need delete from list objects if :
- they have the same field approvalcode. (approvalcode - unique. And can not be more than two identical)
- Of two objects with the same approvalcode, you need to check the one in which the date is greater and and if in this object type = 420. Delete both objects from list.
I decided it like this:
I sort list by approvalcode and date.
List<Transaction> filteredTrans = transResponse.getTransaction().stream().sorted(Comparator.comparing(Transaction::approvalcode).thenComparing(Transaction::getTime)) .collect(Collectors.toList());
After sorting, i compare the two closest objects.
for (int i=0; i<filteredTrans.size()-1; i++) {
if (filteredTrans.get(i).getApprovalcode().equals(filteredTrans.get(j).getApprovalcode()) && filteredTrans.get(j).getType().equals("420")) {
filteredTrans.remove(i);
filteredTrans.remove(j);
j++;
}
}
But I do not like the second part of the code. Can you please advise how it be improved?