将多个对象的实例合并成一个Java中的一个。

huangapple go评论119阅读模式
英文:

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&lt;Car&gt; cars;
}

I have 2 instances of this class

dealer1 = new Dealer(&quot;abc&quot;, [&quot;Acura&quot;, &quot;Honda&quot;]);
dealer2 = new Dealer(&quot;xyz&quot;, [&quot;BMW&quot;, &quot;Audi&quot;]);

There is a list containing both instances:

List&lt;Dealer&gt; 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([&quot;Acura&quot;, &quot;Honda&quot;, &quot;BMW&quot;, &quot;Audi&quot;])

答案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&lt;Car&gt; allCars = dealers.stream()
  .map(Dealer::getCars)
  .flatMap(List::stream)
  .collect(Collectors.toList());
return new Dealer(&quot;Whatever location you want&quot;, allCars);

huangapple
  • 本文由 发表于 2020年7月31日 07:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63182886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定