英文:
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<A>
                .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 < myA.length; ++i) {
  myB[i] = new B(myA[i]);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论