In ArrayList, group by a key and perform summation over one of the values

Aditya Rewari

I have a list of Student objects.

It is required to get create a new list which should be having sum of their marks.

Preferred if this can be done using Java-8

public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student(1, "A", 10));
        list.add(new Student(1, "A", 20));
        list.add(new Student(1, "A", 10));
        list.add(new Student(1, "A", 30));
        list.add(new Student(2, "B", 40));
        list.add(new Student(2, "B", 50));

        Map<String, List<Student>> map = list
                .stream()
                .collect(Collectors.groupingBy(Student::getName));
        System.out.println(map);  // not getting desired result
        
        // Expected Output
        // list [{1, "A", 70}, {2, "B", 90}]

    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {
    int id;
    String name;
    int marks;
}

I get below exception

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 1 (attempted merging values Student(id=1, name=A, marks=10) and Student(id=1, name=A, marks=20))
    at java.base/java.util.stream.Collectors.duplicateKeyException(Collectors.java:135)
    at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:182)
    at java.base/java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
    at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:921)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:682)
    at com.tara.cas.service.Test.main(Test.java:22)

TerZer
public class Test {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        list.add(new Student(1, "A", 10));
        list.add(new Student(1, "A", 20));
        list.add(new Student(1, "A", 10));
        list.add(new Student(1, "A", 30));
        list.add(new Student(2, "B", 40));
        list.add(new Student(2, "B", 50));

        Map<Integer, Student> map = list.stream().collect(Collectors.toMap(Student::getId, Function.identity(),
                (existing, replacement) -> {
                    existing.setMarks(existing.getMarks()+replacement.getMarks());
                    return existing;
                }));

        System.out.println(map.values());
    }
}

class Student {
    int id;
    String name;
    int marks;

    public Student(int id, String name, int marks) {
        this.id = id;
        this.name = name;
        this.marks = marks;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getMarks() {
        return marks;
    }

    public void setMarks(int marks) {
        this.marks = marks;
    }

    @Override
    public String toString() {
        return "{"+id+", \""+name+"\", "+marks+"}";
    }
}

Output:

[{1, "A", 70}, {2, "B", 90}]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Summation/counting over overlapping values or dates with group by over id's in sql

Plotting the summation over different values

Summation over different periods and ranges of values

over reliance on one arrayList

How to perform Arithmetic with ArrayList values

Django: Perform GROUP BY over a view queryset

Plotting values in ggplot over time by group, with condition where one group is one line of the mean, and the other group as individual lines in R

Perform an operation of one element over the rest of the RDD

how to get summation of pair(key) values in a map in java?

Get Multiple values over group by

perform group actions without reducing to one row

Perform Action IF the active sheet is one of a group of sheets

Group by Month and Perform Cumulative Sum of Unique Values

bash loop over two files and one file has two key values

Iterate over array of hashes to sum values of one hash value based on another hash key

Summation over a sympy Array

Map over values of one column

Iterating over values in a HashMap stored within an ArrayList

Group by key + merge array values

Group array values by string in key?

Display values in ArrayList one by one in textView

How to perform group-by over JSON data using JSONATA

How to perform group function over an outer join query?

Iterate over list of dict and group item by key

How do i join and sum values in 3 tables where i need to group by one key column

How to group by more than one key and sum its values in an array of objects, using Lodash?

how to group 59 elements into one element in arraylist?

add values of one group into another group in R

Distribute values of latest date over the group