0

I have some Integers inside of an ArrayList

ArrayList<Integer> al = new AraayList<Integer>();
al.add(100);
al.add(211);

Now I want to split the values in the ArrayList into an array. Suppose 100 is the first value in the ArrayList then the corresponding array should contain 1, 0, 0

1

3 Answers 3

3

If you are using Java 8+ you can use streams with this trick :

List<Integer> result = al.stream()
        .map(String::valueOf) 
        .flatMap(s -> Arrays.stream(s.split("")))
        .map(Integer::valueOf) 
        .collect(Collectors.toList());

Details

  • .map(String::valueOf) this will convert your Integer to String eg. 100 => "100"
  • .flatMap(s -> Arrays.stream(s.split(""))) this will create a Stream by the split with "" eg. "100" => ["1", "0", "0"]
  • .map(Integer::valueOf) this will parse each String to Integer eg. ["1", "0", "0"] => [1, 0, 0]
  • .collect(Collectors.toList()); this will collect all the result in a list eg. [1, 0, 0, 2, 1, 1]
Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer, although it shows one real problem with .stream() ...using // inline comments ... everything turns out pretty unreadable ;-)
I agree @GhostCat I fix it now ;)
0

You can run through the each element in a for loop or foreach since Java 8. Then in the loop you could convert it to a String with

yourNumberAsString = String.valueOf(yourNumberInArray);

With

yourNumberAsString.charAt(0); 

you get the position of the first digit, with 100 it would be 1. If you do that dynamically in another for loop your work is done.

Comments

0

You can iterate over the array, convert the Integer in String and use Split method to get String array:

for(int i=0; i < al.size(); i++)
{
   String [] array = al[i].toString().split("");
   // do whatever you need with the array
}

1 Comment

thanks for sharing this info. below is the code which i am going to use in my project. ArrayList al= new ArrayList(); al.add(100); al.add(200); for(int i=0; i < al.size(); i++) { array = al.get(i).toString().split(""); System.out.println("Size of array is"+array.length); for(int j=0;j<=2;j++) { System.out.println("size at position"+j+" is "+array[j]); } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.