简体   繁体   中英

How to concatenate elements of an array into an integer

There is an array say arr with elements

6,5,1,0,9

I want an integer

a=65109

and

b=90156
    StringBuilder builder = new StringBuilder();
    for(int i = 0;i<arr.length;i++){
        builder.append(arr[i]);
    }
    long a = Long.parseLong(builder.toString());
    long b = Long.parseLong(builder.reverse().toString());
    System.out.println(a);
    System.out.println(b);
int arr[] = {6,5,1,0,9};
int result = 0,reverse = 0;
for (int i = 0; i < arr.length; i++) {
    result= result*10 + arr[i];
    reverse = reverse*10+arr[arr.length-1-i];
}
System.out.println(result);//number 65109
System.out.println(reverse);//number 90156

You can obtain it by using valueOf() method of String class and parseXXX() of Number class. Example code 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 reverse part do modification in for condition as:

for(int i=arr.length-1;i>=0;i--)

Now the for loop will iterate in reverse order on the array.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM