### Question:
PackedEntityCollection extends EntityCollection implements Describable { @Override public Map<Long, List<Entity>> grouped(TypedName<Long> attr) { Preconditions.checkArgument(attr != CommonAttributes.ENTITY_ID, "cannot group by entity ID"); int idx = attributes.lookup(attr); if (idx < 0) { return Collections.emptyMap(); } PackIndex index = indexes[idx]; if (index != null) { return index.getValues() .stream() .collect(Collectors.toMap(l -> (Long) l, l -> new EntityList(index.getPositions(l)))); } else { return stream() .filter(e -> e.hasAttribute(attr)) .collect(Collectors.groupingBy(e -> e.getLong(attr))); } } PackedEntityCollection(EntityType et, AttributeSet attrs, AttrStore[] stores, PackIndex[] idxes, Class<? extends EntityBuilder> ebc); @Override EntityType getType(); @Override LongSet idSet(); @Nullable @Override Entity lookup(long id); @Nonnull @Override List<Entity> find(TypedName<T> name, T value); @Nonnull @Override List<Entity> find(Attribute<T> attr); @Nonnull @Override List<Entity> find(String name, Object value); @Override Map<Long, List<Entity>> grouped(TypedName<Long> attr); @Override List<SortKey> getSortKeys(); Stream<Entity> stream(); @Override Iterator<Entity> iterator(); @Override int size(); @Override String toString(); @Override void describeTo(DescriptionWriter writer);  }### Answer:
@Test public void testGroupEntities() { EntityFactory efac = new EntityFactory(); Rating r1 = efac.rating(100, 200, 3.5); Rating r2 = efac.rating(100, 201, 4.0); Rating r3 = efac.rating(101, 200, 2.0); EntityCollection ec = EntityCollection.newBuilder(CommonTypes.RATING, AttributeSet.create(CommonAttributes.ENTITY_ID, CommonAttributes.USER_ID, CommonAttributes.ITEM_ID, CommonAttributes.RATING)) .add(r1) .add(r2) .add(r3) .addIndex(CommonAttributes.USER_ID) .build(); Map<Long,List<Entity>> groups = ec.grouped(CommonAttributes.USER_ID); assertThat(groups.keySet(), containsInAnyOrder(100L, 101L)); assertThat(groups, hasEntry(equalTo(101L), contains(r3))); assertThat(groups, hasEntry(equalTo(100L), containsInAnyOrder(r1, r2))); groups = ec.grouped(CommonAttributes.ITEM_ID); assertThat(groups.keySet(), containsInAnyOrder(200L, 201L)); assertThat(groups, hasEntry(equalTo(201L), contains(r2))); assertThat(groups, hasEntry(equalTo(200L), containsInAnyOrder(r1, r3))); }