Home > Blockchain >  Transformation of an Array to another Array
Transformation of an Array to another Array

Time:11-10

I need to transform an array of one type to an array of another type.

More specifically, I need to pull just a couple fields from each object in the starting array to create the resulting array, which will contain only those 2 fields, though named differently.

For example, let's say I have an array of Thing objects:

public class Thing {
    private String id;
    private String description;
    ... // other fields
}

I need to create from that an array of Item objects:

public class Item {
    private String code;
    private String data;
    ...
}

... where the id from each Thing becomes code in each Item; and description becomes data.

I've seen examples of using the Stream api to transform an array of objects to an array of Strings. But it's unclear to me thus far how to transform an object to another object.

CodePudding user response:

Try this.

record Thing(String id, String description) {}
record Item(String coded, String data) {}

public static void main(String[] args) {
    Thing[] array = {new Thing("1", "one"), new Thing("2", "two")};
    Item[] transformed = Arrays.stream(array)
        .map(thing -> new Item(thing.id(), thing.description()))
        .toArray(Item[]::new);
    System.out.println(Arrays.toString(transformed));
}

output:

[Item[coded=1, data=one], Item[coded=2, data=two]]
  • Related