【问题标题】:Map object to multiple objects using Java stream使用 Java 流将对象映射到多个对象
【发布时间】:2018-08-24 23:57:52
【问题描述】:

我有一个关于 Java 流的问题。假设我有一个对象流,我想将这些对象中的每一个映射到多个对象。例如像

IntStream.range(0, 10).map(x -> (x, x*x, -x)) //...

在这里,我想将每个值映射到相同的值、平方和相同的值,但符号相反。我找不到任何流操作来做到这一点。我想知道是否最好将每个对象 x 映射到具有这些字段的自定义对象,或者将每个值收集到中间 Map(或任何数据结构)中。

我认为就内存而言,创建自定义对象可能会更好,但也许我错了。

在设计正确性和代码清晰性方面,哪种解决方案会更好?或者也许还有我不知道的更优雅的解决方案?

【问题讨论】:

  • 试试IntStream.range(0, 10).mapToObj(x -> new int[] {x, x*x, -x})
  • 但是对象是任何类型的同一类型?
  • @JoseDaSilva 不是我的情况,但从答案中我认为无论如何都没有直接的方法

标签: java lambda java-8 java-stream


【解决方案1】:

您可以使用flatMap 为原始IntStream 的每个元素生成一个包含3 个元素的IntStream

System.out.println(Arrays.toString(IntStream.range(0, 10)
                                            .flatMap(x -> IntStream.of(x, x*x, -x))
                                            .toArray()));

输出:

[0, 0, 0, 1, 1, -1, 2, 4, -2, 3, 9, -3, 4, 16, -4, 5, 25, -5, 6, 36, -6, 7, 49, -7, 8, 64, -8, 9, 81, -9]

【讨论】:

  • 为此使用外部库的建议答案很荒谬。 1+
【解决方案2】:

除了使用自定义类,例如:

class Triple{
private Integer value;
public Triple(Integer value){
 this.value = value;
}

public Integer getValue(){return this.value;}
public Integer getSquare(){return this.value*this.value;}
public Integer getOpposite(){return this.value*-1;}
public String toString() {return getValue()+", "+this.getSquare()+", "+this.getOpposite();}
}

然后运行

IntStream.range(0, 10)
         .mapToObj(x -> new Triple(x))
         .forEach(System.out::println);

您可以使用 apache commons InmmutableTriple 来执行此操作。 例如:

 IntStream.range(0, 10)
.mapToObj(x -> ImmutableTriple.of(x,x*x,x*-1))
.forEach(System.out::println);

maven 仓库:https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.6

文档:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/tuple/ImmutableTriple.html

【讨论】:

  • 哇哦! ImmutableTriple 的整个库...当 java=9 中存在 Arrays.asListIntStream.ofList.of 等时
  • @eugene 我之前提到过,我们也可以使用自定义类。无论如何,我添加了一个自定义类以供参考。
猜你喜欢
  • 1970-01-01
  • 2016-10-02
  • 2021-04-28
  • 2020-06-27
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
相关资源
最近更新 更多