简体   繁体   中英

Java Stream Api - merge two lists of objects

I am sitting in front of this simple problem and cannot get my head around...maybe its just too late:)
There is a simple "Food" class where a Food has id and amount (imagine shopping list):

public class Food {

    private String id;

    private Integer amount;

}

There is a list of foods that contains one "apple" and another list of foods that contains an "apple" and an "orange". The method addFood should process both lists using stream api and return a list that contains two "apples" and one orange:

List<Food> existingFood = new ArrayList<Food>();
existingFood.add(new Food("apple", 1));

List<Food> foodToAdd = new ArrayList<Food>();
foodToAdd.add(new Food("apple", 1));
foodToAdd.add(new Food("orange", 1));

List<Food> result = addFood(existingFood, foodToAdd);
        
// result should contain:
// 1. {"apple", 2}
// 2. {"orange", 1} 

Whats the most elegant way to do that using stream api? Thanks for your help!

You can use Collectors.groupingBy with Collectors.summingInt :

List<Food> result = Stream.of(existingFood, foodToAdd)
        .flatMap(List::stream)
        .collect(Collectors.groupingBy(Food::getId, Collectors.summingInt(Food::getAmount)))
        .entrySet().stream()
        .map(e -> new Food(e.getKey(), e.getValue().intValue()))
        .collect(Collectors.toList());

Outputs

Food(id=orange, amount=1)
Food(id=apple, amount=2)

Note: the id in the DTOs generally be an Integer or Long, in you case the case the id can be another name, for example name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM