Link to home
Start Free TrialLog in
Avatar of skn73
skn73

asked on

Split an array list in Java

I have an arraylist of >1000 elements.
How do I split it 0-900 in one and the rest in another?

I know I can do a For loop and split it ,.. Is there any other way?
Thanks
Avatar of InteractiveMind
InteractiveMind
Flag of United Kingdom of Great Britain and Northern Ireland image

This is probably less memory-efficient — but probably a better solution in general.


ArrayList list = new ArrayList() ;
.
list.put( new String( "Hello" ) ) ;  // or whatever
.
// if list.size() > 900
String [] block = new String [900] ;  // 0-899
String [] rest   = new Stirng [list.size()-900] ;

String [] array = (String [] ) list.toArray() ;

System.arraycopy( array, 0, block, 0, 900 ) ;
System.arraycopy( rest, 900, rest, 0, list.size()-900 ) ;
I would use ArrayList.clone() followed by ArrayList.removeRange() on each of the two lists.

The clone() method makes a shallow copy of the array list, so creates a copy of the list, but does not copy the objects within the list.  [ In other words, the two lists each point to all the same object instances. ]  Use the removeRange() method to remove the first 1000 elements from one list and the post-1000 elements from the other list.  I like this approach because the items contained within the list do not get duplicated in the process.  

However, it would be naive to assume that iteration does not occur.  It just gets pushed from your code into the methods of ArrayList.
Avatar of wings_gaurav
wings_gaurav

ArrayList list = new ArrayList();
list.add(new Long(0));
list.add(new Long(1));
list.add(new Long(2));
list.add(new Long(3));
list.add(new Long(4));
list.add(new Long(5));
            
ArrayList list1 = new ArrayList(list.subList(0, 3));
ArrayList list2 = new ArrayList(list.subList(3, 6));
            
System.out.println(list1);
System.out.println(list2);

this code will print -
[0, 1, 2]
[3, 4, 5]

-wings
Avatar of skn73

ASKER

The List could be 3000 or 4000 so I need chunks of 900
ASKER CERTIFIED SOLUTION
Avatar of wings_gaurav
wings_gaurav

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial