使用Java流将对象映射到多个对象

fed*_*ngo 6 java lambda java-8 java-stream

我有一个关于 Java 流的问题。假设我有一个对象流,我想将每个对象映射到多个对象。例如类似的东西

IntStream.range(0, 10).map(x -> (x, x*x, -x)) //...
Run Code Online (Sandbox Code Playgroud)

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

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

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

Era*_*ran 5

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

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

输出:

[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]
Run Code Online (Sandbox Code Playgroud)


dsn*_*ode 1

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

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();}
}
Run Code Online (Sandbox Code Playgroud)

并运行

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

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

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

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.asList` 或 `IntStream.of` 或 `List.of` 等时 (3认同)