I'm receiving a List of Entity, I need to group them by 2 fields (periodMonth and periodYear) and return as a new list.
To store the groups, I created a class GroupEntity.
The fields that I must use to group doesn't belong to the Entity itself, but to an embeddable class called EntityPK.
Here's the code of these classes:
Entity
@Entity
@Table(name = "Entity")
public class Entity {
@EmbeddedId
private EntityPK entityPk;
@Column
private String someValue;
EntityPK
@Embeddable
public class EntityPK {
@Column
private String periodMonth;
@Column
private String periodYear;
Group class
public class GroupOfEntity {
private String periodMonth;
private String periodYear;
private List<Entity> entities;
I could iterate over that list and create a map with periodMonth/Year as key, and the List as values, like this:
Set<GroupEntity> listOfGroupEntity = new HashSet<GroupEntity>();
for(Entity entity: listOfEntity) {
GroupEntity groupEntity = new GroupEntity();
groupEntity.setPeriodMonth(entity.getEntityPk().getPeriodMonth());
groupEntity.setPeriodYear(entity.getEntityPk().getPeriodYear());
Optional<GroupEntity> findFirst = listOfGroupEntity.stream().filter(a -> a.equals(groupEntity)).findFirst();
if(findFirst.isPresent()) {
findFirst.get().getEntities().add(entity);
}else {
listOfGroupEntity.add(groupEntity);
}
}
But how could I do that using stream?
Something like
List<GroupEntity> groupEntities
= listOfEntities.stream().collect(Collectors.groupingBy(Entity::getEntityPk::getPeriodMonth,Entity::getEntityPk::getPeriodYear)
And create GroupEntity object for each group, with these entities.
Is it possible?