Home > Mobile >  Java: Convert an array to another
Java: Convert an array to another

Time:06-03

I am converting an array of Strings to an array of MyStrings.

String[] arystrs = { "abc", "xyz" };
MyString[] arymystrs = new MyString[this.arystrs.length];

for (int i = 0; i < arystrs.length; i  ) {
    arymystrs[i] = new MyString(arystrs[i]);  // convert by constructor
}

Is there a more elegant solution (e.g. with collections/streams) beside this one?

I know stream/map/collect is working with collections (list, map) but not sure how it does with an array.

CodePudding user response:

Class::

class MyString {
    private String string;
    public MyString(String string) {
        this.string = string;
    }
}

One line using streams,

MyString[] objects = Arrays.stream(arystrs).map(MyString::new).toArray(MyString[]::new);

Convert the array to stream using Arrays.stream(), map to create object of class MyString and convert to array.

CodePudding user response:

You can use streams:

class MyString {

    private final String str;

    public MyString(String str) {
        this.str = str;
    }

}

String[] arystrs = { "abc", "xyz" };
MyString[] arymystrs = Arrays.stream(arystrs).map(MyString::new).toArray(MyString[]::new);

CodePudding user response:

var myStrings = List.of(arystrs).stream().map(str -> new MyString(str)).collect(Collectors.toList());
/**
*Converts array to list and then stream over. Map each element to MyString. Collect that back to list.
**/

This will return list there might be some syntactical issues because its just typed without any ide. Also for the converted list there is a .toArray() for array conversion if you want.

MyString[] myStringsArray = myStrings.toArray(MyString[]::new);
  • Related