有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个关于Java流的问题。假设我有一个对象流,我想将每个对象映射到多个对象。比如说

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

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

我认为在内存方面,创建自定义对象可能更好,但可能我错了

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


共 (2) 个答案

  1. # 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]
    
  2. # 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 repo: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