0

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?

Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47

2 Answers2

8

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
Eran
  • 387,369
  • 54
  • 702
  • 768
2

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]);
}
TreffnonX
  • 2,924
  • 15
  • 23