如何使用Java 8将对象数组A转换为对象数组B,使用A的构造函数?

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

How to convert Array Of Object A to Array Of Object B with Constructor of A Using Java 8?

问题

我有两个类,Class A 和 Class B。如下所示:

Class A:

class A {

  public String a;

  public A() {

  }

  public A(final String a) {
    this.a = a;
  }
}

Class B:

class B {

  private A a;

  private String b;

  public B() {

  }

  public B(final A a) {
    this.a = a;
  }
}

我正在将 A[] 转换为 B[],如下所示:

public static void main(final String[] args) {

    final A[] myA = new A[3];
    myA[0] = new A("a");
    myA[1] = new A("b");
    myA[2] = new A("c");

    B[] myB = new B[myA.length];

    IntStream.range(0, myA.length).forEach(propIndex->{
      myB[propIndex] = new B(myA[propIndex]);
    });

    System.out.println(myB.length);
}

是否有其他方法可以在不使用索引的情况下完成,类似于toArray(B[]::new)或者其他不需要使用forEach的方式?

英文:

I have two Classes Class A and Class B. As below:

Class A:

class A {

  public String a;

  public A() {

  }

  public A(final String a) {
    this.a = a;
  }
}

Class B:

class B {

  private A a;

  private String b;

  public B() {

  }

  public B(final A a) {
    this.a = a;
  }
}

Where I am converting A[] to B[] as below:

public static void main(final String[] args) {

    final A[] myA = new A[3];
    myA[0] = new A("a");
    myA[1] = new A("b");
    myA[2] = new A("c");
    
    B[] myB = new B[myA.length];

    IntStream.range(0, myA.length).forEach(propIndex->{
      myB[propIndex] = new B(myA[propIndex]);
    });

    System.out.println(myB.length);
}

Is there any other way to do it without iterating(forEach) with Index? Something with toArray(B[]::new) or any other way where I don't have to use forEach?

答案1

得分: 8

可以这样做:

B[] myB = Arrays.stream(myA) // 创建一个 Stream<A>
                .map(B::new) // 将每个 A 的实例映射为 B 的实例
                .toArray(B[]::new); // 收集到 B 的数组
英文:

You can do:

B[] myB = Arrays.stream(myA) // create a Stream&lt;A&gt;
                .map(B::new) // map each instance of A to instance of B
                .toArray(B[]::new); // collect to array of B

答案2

得分: 2

IntStream虽然不是最差的选择,但使用常规循环进行迭代传输可能会更快(尽管有人可能会认为可读性较差)。

B[] myB = new B[myA.length];
for (int i = 0; i < myA.length; ++i) {
  myB[i] = new B(myA[i]);
}
英文:

IntStream is not the worst, though an iterative transfer with a regular loop would probably be faster here (though arguably less readable).

B[] myB = new B[myA.length];
for (int i = 0; i &lt; myA.length; ++i) {
  myB[i] = new B(myA[i]);
}

huangapple
  • 本文由 发表于 2020年10月8日 20:40:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64262757.html
匿名

发表评论

匿名网友

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

确定