I implemented the code for you. If you see the method "group", you'd understand. So these will be no need for pseudo-code.
The Output will be :
[[Football, Baseball, Soccer], [Basketball], [Hockey]]
I also added a new entry :
sport6 - Handball, < Tyler, Reza >
To test algorithm for more than one common list. Output will be:
[[Football, Baseball, Soccer], [Basketball, Handball], [Hockey]]
Here is the code:
public class GroupObjects {
int uniqueIdCounter = 1;
People p1 = new People("Sam",uniqueIdCounter++);
People p2 = new People("Dylan",uniqueIdCounter++);
People p3 = new People("Tyler",uniqueIdCounter++);
People p4 = new People("John",uniqueIdCounter++);
People p5 = new People("Carter",uniqueIdCounter++);
People p6 = new People("Kane",uniqueIdCounter++);
People p7 = new People("Michael",uniqueIdCounter++);
People p8 = new People("Frank",uniqueIdCounter++);
People p9 = new People("Reza",uniqueIdCounter++);
Sport s1 = new Sport("Football", Arrays.asList(p1,p2));
Sport s2 = new Sport("Basketball", Arrays.asList(p3,p4));
Sport s3 = new Sport("Baseball", Arrays.asList(p5,p2));
Sport s4 = new Sport("Hockey", Arrays.asList(p6,p7));
Sport s5 = new Sport("Soccer", Arrays.asList(p5,p8));
Sport s6 = new Sport("Handball", Arrays.asList(p3,p9));
List<Sport> sports = Arrays.asList(s1,s2,s3,s4,s5,s6);
public List<List<Sport>> group(List<Sport> sports){
List<List<Sport>> answerList = new ArrayList<>();
while (!sports.isEmpty()) {
List<Sport> common = new ArrayList<>();
List<Sport> toBeRemoved = new ArrayList<>();
List<People> people = new ArrayList<>();
people.addAll(sports.get(0).getPeopleWhoPlayThisSport());
common.add(sports.get(0));
toBeRemoved.add(sports.get(0));
for (int i = 1; i < sports.size(); i++) {
for (People p : sports.get(i).getPeopleWhoPlayThisSport()) {
if (people.contains(p)) {
people.addAll(sports.get(i).getPeopleWhoPlayThisSport());
common.add(sports.get(i));
toBeRemoved.add(sports.get(i));
break;
}
}
}
sports = sports.stream().filter(sp->!toBeRemoved.contains(sp)).collect(Collectors.toList());
answerList.add(common);
}
return answerList;
}
public static void main(String[] args) {
GroupObjects groupObjects = new GroupObjects();
List<List<Sport>> answer = groupObjects.group(groupObjects.sports);
System.out.println(answer);
}
class Sport {
...
@Override
public String toString() {
return sportsName;
}
Also notice that I have used Java-8 Streams API in my code. So if you are not using Java-8, change that line.
Good Luck!