I'm looking to write code that partitions a given set into disjoint subsets. For example, a set of football players and we partition them depending on the team they belong to. I want in the end a list of representatives, i.e. one player from each team.
All football players know all other player on their team -- this is very relevant for the complexity. So, my current idea on how to do this is as follows (where set
is currently a LinkedHashSet<T>
):
while (!set.isEmpty()) {
E e = set.iterator().next();
makeRepresentative(e);
set.remove(AllPlayersOnSameTeamAs(e));
}
However, it feels weird to build a new iterator in every step of the while-loop. A LinkedHashSet is supposed to have some kind of firstElement()
function internally (for its LinkedList behaviour), but for some reason I can't find how to do this. I also tried a foreach loop instead, but that resulted in a java.util.ConcurrentModificationException
.
How am I supposed to do this correctly?