SelectedGroup implements Grouped, Iterable<T> { @Override public Groups groups() { final ImmutableSet.Builder<String> groups = ImmutableSet.builder(); for (final T member : members) { groups.addAll(member.groups()); } return new Groups(groups.build()); } SelectedGroup(final Set<T> members); Set<T> getMembers(); @Override Iterator<T> iterator(); Stream<T> stream(); boolean isEmpty(); @Override Groups groups(); int size();  }
@Test public void testMergedGroups() { final Grouped a = Mockito.mock(Grouped.class); final Grouped b = Mockito.mock(Grouped.class); Mockito.when(a.groups()).thenReturn(groupA); Mockito.when(b.groups()).thenReturn(groupB); final SelectedGroup<Grouped> g = new SelectedGroup<>(ImmutableSet.of(a, b)); Assert.assertEquals(ImmutableSortedSet.of("bar", "baz", "foo"), ImmutableSortedSet.copyOf(g.groups())); }