Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to combine consecutive similar objects that are in a Java Stream?

Till now I could not find a good solution, so I hope you can help.

Suppose we have a class like the following:

class Someclass {
     String type;
     int count;
}

When having a Stream { "a", 1 }, { "a", 2}, { "b", 4}, { "b", "5" } and that needs to be processed as { "a", 3 }, { "b", 9 }.

Combining means of course, adding the counts for the objects with the same type.

How to do?

question from:https://stackoverflow.com/questions/65943016/combine-similar-elements-in-a-java-stream

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
215 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use Collectors.toMap to collect the stream into the desired Map.

Demo:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class MyType {
    String type;
    int count;

    public MyType(String type, int count) {
        this.type = type;
        this.count = count;
    }

    public String getType() {
        return type;
    }

    public int getCount() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        List<MyType> list = List.of(new MyType("a", 1), 
                                    new MyType("a", 2), 
                                    new MyType("b", 4), 
                                    new MyType("b", 5));

        Map<String, Integer> map = list.stream()
                .collect(Collectors.toMap(MyType::getType, MyType::getCount, Integer::sum));

        System.out.println(map);
    }
}

Output:

{a=3, b=9}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...