Consider a flat int[] holding the change indices, rather than a list of pairs, since you're toggling between true and false. Here is a tested implementation using this paradigm, plus generating the sublists using List.subList().
import java.util.*;
public class Main
{
public static void main(String[] args) {
List<Person> people =
Arrays.asList(new Person(true), new Person(false),
new Person(true), new Person(true), new Person(false),
new Person(false), new Person(true));
int[] changes = new int[people.size() + 1]; // allow for max changes
Arrays.fill(changes, -1); // if an index is not used, will remain -1
changes[0] = 0;
int change = 1;
boolean eligible = people.isEmpty() ? false : people.get(0).isEligible();
for (int i = 1; i < people.size(); i++) {
Person person = people.get(i);
if (eligible != person.isEligible()) {
changes[change++] = i;
eligible = person.isEligible();
}
}
changes[change] = people.size(); // end of last change segment
List<List<Person>> sublists = new ArrayList<List<Person>>(change);
for (int i = 0; i < change; i++) {
sublists.add(people.subList(changes[i], changes[i + 1]));
}
System.out.println(sublists);
}
}
Note that no copies are made of people or its elements; the sublists are merely views into the original list. The above code assumes a Person class defined something like this:
class Person
{
boolean eligible;
Person(boolean eligible) {
this.eligible = eligible;
}
boolean isEligible() {
return this.eligible;
}
@Override
public String toString() {
return "Person(" + isEligible() + ")";
}
}
subList()method; it makes virtual sublists which are actually views into the original list.Map<XX, Person>whereXXis the class ofeligible?