Since you say it's a List
, you can use subList()
to split it:
int midpoint = myRecords.size() / 2;
List<MyRecord> asList = (List<MyRecord>)myRecords;
List<MyRecord> part1 = asList.subList(0, midpoint);
List<MyRecord> part2 = asList.subList(midpoint, asList.size());
part1
will be the smaller one if there are an odd number of items. To make part2
the smaller one, change the first line to:
int midpoint = (myRecords.size() + 1) / 2;
Note that the sublists are actually a view to the underlying full list. If you want to disconnect it (to reduce the memory footprint or to prevent modification), you can do so by copying them each to a new list:
List<MyRecord> part1 = new ArrayList<>(asList.subList(0, midpoint));
List<MyRecord> part2 = new ArrayList<>(asList.subList(midpoint, asList.size()));
If you want a solution that works for any Collection
type, you'll need to use its Iterator
:
List<MyRecord> part1 = new ArrayList<>();
List<MyRecord> part2 = new ArrayList<>();
Iterator<MyRecord> iter = myRecords.iterator();
for (int i = 0; iter.hasNext(); i++) {
(i < midpoint ? part1 : part2).add(iter.next());
}