Home > Blockchain >  How to call values of ArrayList inside for loop, from outside the loop JAVA?
How to call values of ArrayList inside for loop, from outside the loop JAVA?

Time:07-12

I'm new to programming. I was coding this Java ArrayList. I need the array of values which I get from a for loop to get outside of the loop to make more calculations. How can I get it done? Here I need 309 as an int outside the loop.

ArrayList<Integer> idNumber = new ArrayList(12);    //creat arraylist  
idNumber.add(1);
idNumber.add(9);
idNumber.add(9);
idNumber.add(9);
idNumber.add(3);
idNumber.add(0);
idNumber.add(9);
idNumber.add(0);
idNumber.add(4);
idNumber.add(6);
idNumber.add(7);
idNumber.add(0);

System.out.println(idNumber);  

for(int i = 4; i < 7; i  ) {
    System.out.print(idNumber.get(i));  
}

CodePudding user response:

Something basic like below might work for you. But if it's for a larger set of indexes, you can use a StringBuilder.

String result = "";

for(int i = 4; i<7; i  )  {
    result = result idNumber.get(i);
}
System.out.print(result);

CodePudding user response:

I believe the following achieves what you want.

ArrayList<Integer> idNumber = new ArrayList(12);    //creat arraylist  
idNumber.add(1);
idNumber.add(9);
idNumber.add(9);
idNumber.add(9);
idNumber.add(3);
idNumber.add(0);
idNumber.add(9);
idNumber.add(0);
idNumber.add(4);
idNumber.add(6);
idNumber.add(7);
idNumber.add(0);

System.out.println(idNumber);  
int amount = 0;
for(int i = 4; i < 7; i  ) {
    amount = amount * 10   idNumber.get(i);
}
System.out.print(amount);  

Running the above code prints 309.

Alternatively, you could use the stream API

// import java.util.stream.Collectors;

Integer value = idNumber.stream()
                        .skip(4)
                        .limit(3)
                        .collect(Collectors.reducing(Integer.valueOf(0), (a, i) -> a * 10   i));
System.out.println(value);

You can see the complete code here: https://www.jdoodle.com/iembed/v0/t8k

  • Related