user8341360
user8341360

Reputation:

Conversion of arrays in java

Assume we have an array of integers, say int[] x={0,1,2,3};

Can I convert x into an array of type String? Can I upcast x into an array of doubles? By the above conversions, I mean converting all entries of the array collectively, not individually.

How do generally conversions 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?

Upvotes: 3

Views: 3056

Answers (5)

Raju Sharma
Raju Sharma

Reputation: 2516

You can possibly do casting from int , double , float etc. to String using one liner code as below:

int[] x={0,1,2,3};
String stringArray=Arrays.toString(x);

But to cast from int to double you would need to iterate and cast it individually in loop.

With java8, it is possible using streams

long[] longArray = Arrays.stream(x).mapToLong(i -> i).toArray();
double[] doubleArray = Arrays.stream(x).mapToDouble(i -> i).toArray();

Upvotes: 2

user3145373 ツ
user3145373 ツ

Reputation: 8156

In java8 you can do:

    int[] x = {0,1,2,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.

Upvotes: 4

user4906240
user4906240

Reputation: 625

With Java 8 it is possible in one line you can do this

int[] x = {0,1,2,3};
double[] doubles = Arrays.stream(x).asDoubleStream().toArray();

Upvotes: 6

Bhargav Modi
Bhargav Modi

Reputation: 2655

To convert int into string array you can use Stream

String[] strinArray=  Arrays.Stream(nums).mapToObj(String::valueOf).toArray(String[]::new); //where nums is int array

another way is

String[] strinArray = Arrays.toString(nums).replaceAll("[\\[\\]]", "").split("\\s*,\\s*");

To convert int into double you can use below snippet

double[] doubles = Arrays.stream(nums).asDoubleStream().toArray();

Note : Above code will work in java 8 only

Upvotes: 3

Abhishek Honey
Abhishek Honey

Reputation: 645

You can also convert an int array to String array without using stream methods or if you are using lower version of java.

import java.util.Arrays;

public class test {
    public static void main(String[] args) {
        int[] x = { 0, 1, 2, 3 };
        String[] stringArray = Arrays.toString(x).split("[\\[\\]]")[1].split(", ");
        System.out.println(Arrays.toString(stringArray));
    }

}

Upvotes: 0

Related Questions