英文:
Merge multiple instances of an object into one in Java
问题
我有一个类
class Dealer {
String location;
List<Car> cars;
}
我有两个这个类的实例
dealer1 = new Dealer("abc", ["Acura", "Honda"]);
dealer2 = new Dealer("xyz", ["BMW", "Audi"]);
有一个包含这两个实例的列表:
List<Dealer> dealers = [dealer1, dealer2];
是否有一种Java Stream的方式将经销商列表合并为一个经销商,独立于位置但合并所有经销商可用的汽车列表?
最终的结果对象:
Dealer(["Acura", "Honda", "BMW", "Audi"])
英文:
I have a class
class Dealer {
String location;
List<Car> cars;
}
I have 2 instances of this class
dealer1 = new Dealer("abc", ["Acura", "Honda"]);
dealer2 = new Dealer("xyz", ["BMW", "Audi"]);
There is a list containing both instances:
List<Dealer> dealers = [dealer1, dealer2];
Is there a Java Stream way to merge the list of dealers into a single dealer, independent of the location but combining the list of cars available for all dealers ?
Final resultant object:
Dealer(["Acura", "Honda", "BMW", "Audi"])
答案1
得分: 2
当然。但是这不会特别美观,因为它有点奇怪。将经销商分解为汽车,将您的“流的流”扁平映射成一个流(这就是flatmap的作用;它允许您将一个对象映射到一个流中,然后将所有流“展开”成一个单一的流),然后收集回列表,然后使用它来创建一个新的经销商。
List<Car> allCars = dealers.stream()
.map(Dealer::getCars)
.flatMap(List::stream)
.collect(Collectors.toList());
return new Dealer("您想要的任何位置", allCars);
请注意,上述代码是Java代码,用于将经销商的汽车列表展平,并创建一个新的经销商对象。
英文:
Sure. But it's not going to be particularly pretty because it's a bit odd. Break dealers down into cars, flatmap your 'stream of streams' into just a stream (that's what flatmap does; lets you map an object into a stream and then 'unpack' all streams into a single stream), and then collect back to list, and use that to make a new dealer.
List<Car> allCars = dealers.stream()
.map(Dealer::getCars)
.flatMap(List::stream)
.collect(Collectors.toList());
return new Dealer("Whatever location you want", allCars);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论