英文:
Java Stream Api - merge two lists of objects
问题
我坐在这个简单的问题面前,却无法理解... 也许现在太晚了 :) <br>
有一个简单的“食物”类,其中食物有id和数量(想象购物清单):
public class Food {
private String id;
private Integer amount;
}
有一个包含一个“苹果”的食物列表,还有另一个包含一个“苹果”和一个“橙子”的食物列表。方法addFood应使用流API处理这两个列表,并返回一个包含两个“苹果”和一个“橙子”的列表:
List
existingFood.add(new Food("apple", 1));
List
foodToAdd.add(new Food("apple", 1));
foodToAdd.add(new Food("orange", 1));
List
// result应包含:
// 1. {"apple", 2}
// 2. {"orange", 1}
使用流API完成这个问题的最优雅方式是什么?
感谢您的帮助!
英文:
I am sitting in front of this simple problem and cannot get my head around...maybe its just too late <br>
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!
答案1
得分: 0
你可以使用 Collectors.groupingBy
结合 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());
输出:
Food(id=orange, amount=1)
Food(id=apple, amount=2)
注意:在DTO中,通常id是整数或长整型。在您的情况下,id可以是另一个名称,例如 name
。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论