Reputation: 707
I have data on following pattern and I just want to add the number of similar items and stored in a List. Whereas , the items like quantity= 1, ingredient=chicken, unit =kg
,
The unit will be always kg. I have List<itemsDTO>
I want to add similar items from this list. [{1,"kg","chicken"} , {2.2,"kg","beaf"} , {0.25,"kg","chicken"}]
public class itemsDTO {
double quantity;
String unit;
String ingredient;
}
I have tried this code
List<itemsDTO> itemsDTOList = new ArrayList<>();
for (int i = 0; i < itemsDTOList.size(); i++) {
for (int j = 0; j < itemsDTOList.size(); j++) {
if (itemsDTOList.get(i).getIngredient().equalsIgnoreCase(itemsDTOList.get(j).getIngredient())) {
int sum;
sum = itemsDTOList.get(i).getQuantity() + itemsDTOList.get(j).getQuantity();
}
}
}
Expected Output 1.25 kg chicken,2.2 kg beaf
Upvotes: 0
Views: 63
Reputation: 17289
You can use toMap
collector with merge function:
BinaryOperator<itemsDTO> sumQuantity = (a, b) -> {
a.setQuantity(a.getQuantity() + b.getQuantity());
return a;
};
itemsDTOList.stream()
.collect(Collectors.toMap(itemsDTO::getIngredient, Function.identity(), sumQuantity))
.values();
Upvotes: 3