Reputation: 25
I have a list of objects in ArrayList.I want to remove the duplicate object in the list based on old paymentDate.For an Example, if the member (Vishal) repeated two times I need to remove the Vishal object based on old paymnetDate from the list.
[{CreditCardNum,name,Amount,DueDate,PaymentDate}]
masterlist = [{4123456789123456,Vishal,80000,03/06/2015,07/06/2015},
{4123456789123456,Vivek,80000,07/06/2015,11/06/2015},
{4123456789123456,Vishal,80000,03/06/2015,09/06/2015}];
Removable Object from List =
{4123456789123456,Vishal,80000,03/06/2015,07/06/2015}
List<CreditcardVo> masterlist =new ArrayList<CreditcardVo>();
public class CreditCardVO {
public String creditNumber;
public String name;
public int amount;
public Date dueDate;
public Date paymentDate;
public String getCreditNumber() {
return creditNumber;
}
public void setCreditNumber(String creditNumber) {
this.creditNumber = creditNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getPaymentDate() {
return paymentDate;
}
public void setPaymentDate(Date paymentDate) {
this.paymentDate = paymentDate;``
}
}
Upvotes: 0
Views: 67
Reputation: 218
Here is the algorithm that you can use to do that: First You need a unique identifier for each of the object in the ArrayList. The identifier can me the name if you are sure that the name does not repeat.
val
associated to that identifier in the map and compare it its date with the date of your current object curr
:
val
has the latest date then do nothingcurr
has the latest date then call map.put(identifier, curr)
to update the value in the mapmap.put(identifier, curr)
to add the current object to the mapAt the end, the result will be the values of the map. And you can get that by using map.values()
Upvotes: 1
Reputation: 56423
You can create a method as such:
List<CreditCardVO> getDistinctObjectsByName(List<CreditCardVO> cardVOS){
Collection<CreditCardVO> resultSet =
cardVOS.stream()
.collect(Collectors.toMap(CreditCardVO::getName, Function.identity(),
(left, right) ->
left.getPaymentDate().after(right.getPaymentDate()) ?
left : right
)).values();
return new ArrayList<>(resultSet);
}
which given a list of CreditCardVO
will return a new list with distinct objects with the latest payment date.
Upvotes: 0