There's probably a Java 8 one-liner out there, but I prefer to shy away from those if I need to. Note that this solution is exclusively in Java 8.
Essentially, the process you need to follow:
- Split up your elements into the appropriate buckets (by user ID)
- Combine the elements together
- Return a new list containing an individual element.
You don't specify which customLabel
wins out overall, but here's an approach that merges it with the last one.
Add this method to Customs
:
public void combine(Customs another) {
this.userId = another.getUserId();
this.customLabel = another.getCustomLabel();
this.itemPrice = null == this.itemPrice ? another.getItemPrice() : this.itemPrice + another.getItemPrice();
this.weight = null == this.weight ? another.getWeight() : this.weight + another.getWeight();
}
The following lines of code break down the above steps. I'm using a collector here to combine the elements together in the final phase. As I go along, I'm basically adding the elements into another list for final parsing.
final Map<String, List<Customs>> groupedCustomsElements = customsList.stream()
.collect(Collectors.groupingBy(Customs::getUserId));
final List<Customs> combinedResult = new ArrayList<>();
for (String s : groupedCustomsElements.keySet()) {
combinedResult.add(groupedCustomsElements.get(s)
.stream()
.collect(Customs::new, Customs::combine, Customs::combine));
}
A cleaner solution may be to create your own custom list which extends ArrayList
and augment the add
method to suit your needs.
class CustomCombiningList extends ArrayList<Customs> {
@Override
public boolean add(Customs e) {
int idx = indexOf(e);
if(idx != -1) {
add(idx, get(idx).combineAndReturn(e));
remove(idx + 1); // clean up unneeded object; worth a unit test
} else {
super.add(e);
}
return true;
}
}
This would require two new methods - combineAndReturn
which actually returns the result of combine
, and a definition of equals()
for your Customs
element. It may be a sight prettier to read than the convoluted lambda, too.