How to concatenate elements of an array into an integer
4 answers
You can get it using the valueOf () method of the String class and parseXXX () of the Number class. Sample snippet below:
class Test{
public static void main(String[] args){
int[] arr={6,5,1,0,9};
String str="";
for(int i=0;i<arr.length;i++){
int x=arr[i];
str=str+String.valueOf(x);
}
int concatenated=Integer.parseInt(str);
System.out.println(concatenated);
}
}
For the reverse part, modify the condition as:
for(int i=arr.length-1;i>=0;i--)
Now the for loop will iterate in reverse order in the array.
+2
source to share
IN Java 8
code:
List<Integer> list = Arrays.asList(6, 5, 1, 0, 9);
int value = Integer.parseInt(list.stream()
.map(i -> Integer.toString(i))
.reduce("", String::concat));
System.out.println(value);
Collections.reverse(list);
int ReverseValue = Integer.parseInt(list.stream()
.map(i -> Integer.toString(i))
.reduce("", String::concat));
System.out.println(ReverseValue);
output:
65109 90156
0
source to share