user11888222
user11888222

Reputation:

group multiple elements of a collection when they have one common attribute

I have a collection of multiple elements, the are like

id: 18    quantity:20
id: 18    quantity:70
id: 21    quantity:50

how to I take this collection and make it:

id:18    quantity:90
id:21    quantity:50

I am using java

Upvotes: 0

Views: 30

Answers (1)

edean
edean

Reputation: 496

You would want to collect it into a map, like that:

public class Playground {
    public static void main(String... args) {
        List<ArticlePos> articlePos = Arrays.asList(new ArticlePos("18", 20), new ArticlePos("18", 70), new ArticlePos("21", 50));
        Map<String, Integer> collected = articlePos.stream().collect(Collectors.toMap(ArticlePos::getId, ArticlePos::getAmount, Integer::sum));
        collected.entrySet().forEach(System.out::println);

    }
    
    private static class ArticlePos {

        public ArticlePos(String id, Integer amount) {
            this.id = id;
            this.amount = amount;
        }
        public String id;
        public Integer amount;

        public String getId() {
            return id;
        }
        public Integer getAmount() {
            return amount;
        }
    }
}

As you did not show a lot of code, you need to implement it yourself adjusted to your situation of course. So this is not really a Copy-paste-solution. However, it's quite simple.

Collectors.toMap() requires a KeyMapper-, ValueMapper- and a Merge-Function. For KeyMapper, I simply take the ID-Getter, for Value the Amount-Getter and eventually Merging the amounts happens bei obviously adding to each other.

Read function documentation

Upvotes: 1

Related Questions