I have implemented the code for you. If you see the "group" method, you will understand. Thus, this will not be necessary for pseudocode. The output will be:
[[Football, Baseball, Football], [Basketball], [Hockey]]
I also added a new entry:
sport6 โโ- Handball, Tyler, Resa>
To check the algorithm for more than one common list. The output will be:
[[Football, Baseball, Football], [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 note that I used the Java-8 Streams API in my code. Therefore, if you are not using Java-8, change this line.
Good luck