0

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

1 Answer 1

3

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();
Sign up to request clarification or add additional context in comments.

12 Comments

What is the list in your answer? @Hadi J
I meant itemsDTOList
It is possible that I have chicken is more than 2 times. So, does it work for that condition too?
Yes, it is possible. toMap collectors with merge function merge all object with same ingredient
@Lily, i think this solution is absolutely perfect. you should also try by yourself something. itemsDTOS.stream().collect(Collectors.toMap(ItemsDTO::getIngredient, Function.identity(), sumQuantity)) .values() .stream() .map(itemsDTO -> itemsDTO.getQuantity() + " " + itemsDTO.getUnit() + " " + itemsDTO.getIngredient()) .collect(Collectors.toList()); But above comment is perfect. you would call itemDTO.toString and override toString in your itemDTO class, which will return quantity + " " + unit + " " + ingredient;
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.