List<Registration> sortRegistrations(List<Registration> registrations) { // Count the number of distinct groups in the registrations list. int groupCount = (int) registrations.stream() .map(r -> r.member().groupId()) .distinct() .count(); Set<MemberGroupId> groups = new HashSet<>(); List<Registration> sortedRegistrations = new LinkedList<>(); // Loop until all registrations have been sorted. while (!registrations.isEmpty()) { // Clear the list of consumed groups. groups.clear(); // For each registration, check if it can be added to the registrations list. Iterator<Registration> iterator = registrations.iterator(); while (iterator.hasNext()) { Registration registration = iterator.next(); // If the registration's group has not been added to the list, add the registration. if (groups.add(registration.member().groupId())) { sortedRegistrations.add(registration); iterator.remove(); // If an instance of a registration from each group has been added, reset the list of registrations. if (groups.size() == groupCount) { groups.clear(); } } } } return sortedRegistrations; }