1

I have a Collection of objects:

Collection<MyRecord> myRecords

How can I split this Collection into 2 different collections, which are equal in size?

Edit:

  • I want to split the collection based on the number of records i.e., if it has 400 records, it should split into 2 different Collections of 200 size each.

  • It is a list.

  • No, the order does not matter.
NoName
  • 1,509
  • 2
  • 20
  • 36
  • That is very broad subject. How exactly do you want to split it? What are the properties of this collection (is it perhaps list, set, queue, other...)? Is it ordered collection? Is order of elements relevant to insertion of elements or on elements properties? Also what if amount of elements is odd? – Pshemo Feb 02 '18 at 00:04
  • If it is a list then use proper type for it. So instead of `Collection` use `List` interface which provides `subList` method. – Pshemo Feb 02 '18 at 00:15

1 Answers1

1

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());
}
shmosel
  • 49,289
  • 6
  • 73
  • 138