Converting from <Datatype1>[] to <Datatype2>[]

Total Post:21

Points:147
 1069  View(s)
Ratings:
Rate this:
Is it possible to convert from a list of datatypes without going through the trouble of looping through the entire list.

I.e:b = {"1", "2"}; 
Integer[] a = (Integer[]) b; //not actually runnable

Not really necessary, but it would be nice.
  1. Post:397

    Points:3117
    Re: Converting from <Datatype1>[] to <Datatype2>[]

    In Java 8, you can do
    Integer[] integerArray = 
        Stream.of(stringArray)
              .map(Integer::parseInt)
              .toArray(Integer[]::new);
    If you want an int-Array, you can do:
    int[] intArray = 
    Stream.of(stringArray)
          .mapToInt(Integer::parseInt)
          .toArray();
    Stream.of() creates a stream from the array. map maps every element of the stream to an Integer using Integer::parseInt. Using mapToInt, you can create an Intstream, which is a specialization of streams for integer primitives. Integer[]::new is a method reference to an array constructor.

    This assumes all elements of the array are parseable, if not it will throw an exception.

Answer