Converting arrays in Java

Suppose we have an array of integers, such as int [] x = {0,1,2,3};

Can I convert x to an array of string type? Can I convert x to doubles array? Through the above conversion, I mean to convert all the entries of the array together, not separately

How do general transformations work for arrays in Java? Do I have to convert each entry of the original array and assign it to the corresponding entry of the target array?

Solution

In Java 8, you can do this:

int[] x = {0,3};
    // int to double
    double[] doublesArray = Arrays.stream(x).asDoubleStream().toArray();
    //int to string
    String[] stringArray = Arrays.stream(x).mapToObj(String::valueOf).toArray(String[]::new);
    // string to double
    double[] doublesArrayFromString = Arrays.stream(stringArray).mapToDouble(Double::valueOf).toArray();

    Arrays.stream(doublesArray).forEach(System.out::println);
    Arrays.stream(stringArray).forEach(System.out::println);
    Arrays.stream(doublesArrayFromString).forEach(System.out::println);

Here's running code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>