Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.8k views
in Technique[技术] by (71.8m points)

java - How to add two stream elements together?

I am new to streams and collections.I have a class foo with a name and number of balls which each person has. I have this as a list of foo objects.I would like to search if two foo objects have the same name and add their balls together and give of names back based on the lowest no of balls. So I know how to do this with loops.How is this possible to do with streams? Thank you


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

1 Reply

0 votes
by (71.8m points)

This might work for you:

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


class Foo {
    String name;
    Integer noOfBalls;

    public Foo(String name, Integer noOfBalls) {
        this.name = name;
        this.noOfBalls = noOfBalls;
    }

    public String getName() {
        return name;
    }

    public Integer getNoOfBalls() {
        return noOfBalls;
    }

    @Override
    public String toString() {
        return "Foo{" +
                "name='" + name + ''' +
                ", noOfBalls=" + noOfBalls +
                '}';
    }
}
public class Test {

    public static void main(String[] args){
        ArrayList<Foo> arrayList = new ArrayList<>();
        arrayList.add(new Foo("John",10));
        arrayList.add(new Foo("Babu",1));
        arrayList.add(new Foo("Alex",5));
        arrayList.add(new Foo("Babu",5));
        arrayList.add(new Foo("John",10));
        ArrayList<Foo> arrayListTemp = arrayList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toMap(Foo::getName, Function.identity(), (left, right) -> {
                    left.noOfBalls= left.noOfBalls + right.noOfBalls;
                    return left;
                }), m -> new ArrayList<>(m.values())));
        arrayListTemp.sort(Comparator.comparingInt(Foo::getNoOfBalls));
        arrayListTemp.forEach(System.out::println);

    }

}

Here I am converting list to map(key as name and value as Foo object) and if the name already exists then merging Foo object by adding noOfBalls.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...