With streams added in Java 8 we can write code like:
int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
The simple
Stream#toArrayreturns anObject[]array, so it is not what we want. Also,Stream#toArray(IntFunction<A[]> generator)which returnsA[]doesn't do what we want, because the generic typeAcan't represent the primitive typeintSo it would be nice to have some kind of stream which would be designed to handle primitive type
intinstead of the reference type likeInteger, because itstoArraymethod will most likely also return anint[]array (returning something else likeObject[]or even boxedInteger[]would be unnatural forint). And fortunately Java 8 has such a stream which isIntStreamSo now the only thing we need to figure out is how to convert our
Stream<Integer>(which will be returned fromlist.stream()) to that shinyIntStream.Quick searching in documentation of
Streamwhile looking for methods which returnIntStreampoints us to our solution which ismapToInt(ToIntFunction<? super T> mapper)method. All we need to do is provide a mapping fromIntegertoint.Since
ToIntFunctionis functional interface we can also provide its instance via lambda or method reference.Anyway to convert Integer to int we can use
Integer#intValueso insidemapToIntwe can write:mapToInt( (Integer i) -> i.intValue() )(or some may prefer:
mapToInt(Integer::intValue).)But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type
int(the lambda used inmapToIntis an implementation of theToIntFunctioninterface which expects as body a method of type:int applyAsInt(T value)which is expected to return anint).So we can simply write:
mapToInt((Integer i)->i)Also, since the
Integertype in(Integer i)can be inferred by the compiler becauseList<Integer>#stream()returns aStream<Integer>, we can also skip it which leaves us withmapToInt(i -> i)
With streams added in Java 8 we can write code like:
int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
The simple
Stream#toArrayreturns anObject[]array, so it is not what we want. Also,Stream#toArray(IntFunction<A[]> generator)which returnsA[]doesn't do what we want, because the generic typeAcan't represent the primitive typeintSo it would be nice to have some kind of stream which would be designed to handle primitive type
intinstead of the reference type likeInteger, because itstoArraymethod will most likely also return anint[]array (returning something else likeObject[]or even boxedInteger[]would be unnatural forint). And fortunately Java 8 has such a stream which isIntStreamSo now the only thing we need to figure out is how to convert our
Stream<Integer>(which will be returned fromlist.stream()) to that shinyIntStream.Quick searching in documentation of
Streamwhile looking for methods which returnIntStreampoints us to our solution which ismapToInt(ToIntFunction<? super T> mapper)method. All we need to do is provide a mapping fromIntegertoint.Since
ToIntFunctionis functional interface we can also provide its instance via lambda or method reference.Anyway to convert Integer to int we can use
Integer#intValueso insidemapToIntwe can write:mapToInt( (Integer i) -> i.intValue() )(or some may prefer:
mapToInt(Integer::intValue).)But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type
int(the lambda used inmapToIntis an implementation of theToIntFunctioninterface which expects as body a method of type:int applyAsInt(T value)which is expected to return anint).So we can simply write:
mapToInt((Integer i)->i)Also, since the
Integertype in(Integer i)can be inferred by the compiler becauseList<Integer>#stream()returns aStream<Integer>, we can also skip it which leaves us withmapToInt(i -> i)
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
List<T>.toArraywon't work because there's no conversion fromIntegertoint- You can't use
intas a type argument for generics, so it would have to be anint-specific method (or one which used reflection to do nasty trickery).
I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(
Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).
Videos
Native Java 8 (one line)
With Java 8, int[] can be converted to Integer[] easily:
int[] data = {1,2,3,4,5,6,7,8,9,10};
// To boxed array
Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );
// To boxed list
List<Integer> you = Arrays.stream( data ).boxed().collect( Collectors.toList() );
List<Integer> like = IntStream.of( data ).boxed().collect( Collectors.toList() );
As others stated, Integer[] is usually not a good map key.
But as far as conversion goes, we now have a relatively clean and native code.
If you want to convert an int[] to an Integer[], there isn't an automated way to do it in the JDK. However, you can do something like this:
int[] oldArray;
... // Here you would assign and fill oldArray
Integer[] newArray = new Integer[oldArray.length];
int i = 0;
for (int value : oldArray) {
newArray[i++] = Integer.valueOf(value);
}
If you have access to the Apache lang library, then you can use the ArrayUtils.toObject(int[]) method like this:
Integer[] newArray = ArrayUtils.toObject(oldArray);
Start with a result of 0. Loop through all elements of your int array. Multiply the result by 10, then add in the current number from the array. At the end of the loop, you have your result.
- Result: 0
- Loop 1: Result * 10 => 0, Result + 1 => 1
- Loop 2: Result * 10 => 10, Result + 2 => 12
- Loop 3: Result * 10 >= 120, Result + 3 => 123
This can be generalized for any base by changing the base from 10 (here) to something else, such as 16 for hexadecimal.
You have to cycle in the array and add the right value. The right value is the current element in the array multiplied by 10^position.
So: ar[0]*1 + ar[1]*10 + ar[2] *100 + .....
int res=0;
for(int i=0;i<ar.length;i++) {
res=res*10+ar[i];
}
Or
for(int i=0,exp=ar.length-1;i<ar.length;i++,exp--)
res+=ar[i]*Math.pow(10, exp);
Suppose we have a List<Employee> object and we want to convert it into Employee[ ].
List<Employee> list=new ArrayList<>();
We can convert list to object type array in following ways:
Employee[] empArray = list.toArray(new Employee[0]);
or
Employee[] empArray = new Employee[list.size()];
list.toArray(empArray);
But to convert arrays to primitive types. you have to convert it into following way:-
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Is there any other way to convert List to its specific type of array?
You can convert entire string and then you get the toCharArray method separately characters in an array
Scanner t = new Scanner(System.in);
int x = t.nextInt();
char[] xd = String.valueOf(x).toCharArray();
for (int i = 0; i < xd.length; i++) {
System.out.println(xd[i]);
}
Another way of doing this would be:
int test = 12345;
int[] testArray = new int[String.valueOf(test).length()];
And then looping over it.
int x = 10382;
String[] str1 = Integer.toString(x).split("");
for(int i=0;i<str1.length;i++){
System.out.println(str1[i]);
}