• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 7320
  • Last Modified:

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
0
skn73
Asked:
skn73
1 Solution
 
InteractiveMindCommented:
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 ) ;
0
 
brettmjohnsonCommented:
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.
0
 
wings_gauravCommented:
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
0
 
skn73Author Commented:
The List could be 3000 or 4000 so I need chunks of 900
0
 
wings_gauravCommented:
If the output list can be multiple then make an array of ArrayLists. calculate the count required by didviding the total by 900. Add in loop that steps 900.  i.e. lists[i] = new ArrayList(list.subList(x , x + 900)); i++; x += 900;

-wings
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now