我收到一個實體列表,我需要將它們按 2 個字段(periodMonth 和 periodYear)分組并作為新列表返回。為了存儲組,我創建了一個類 GroupEntity。我必須用來分組的字段不屬于實體本身,而是屬于一個名為 EntityPK 的可嵌入類。下面是這些類的代碼:實體@Entity@Table(name = "Entity")public class Entity { @EmbeddedId private EntityPK entityPk; @Column private String someValue;實體PK@Embeddablepublic class EntityPK { @Column private String periodMonth; @Column private String periodYear;團體課public class GroupOfEntity { private String periodMonth; private String periodYear; private List<Entity> entities;我可以遍歷該列表并創建一個以 periodMonth/Year 為鍵、以 List 為值的地圖,如下所示: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); } }但是我怎么能用流來做到這一點呢?就像是List<GroupEntity> groupEntities = listOfEntities.stream().collect(Collectors.groupingBy(Entity::getEntityPk::getPeriodMonth,Entity::getEntityPk::getPeriodYear)并使用這些實體為每個組創建 GroupEntity 對象。是否可以?
如何使用流從 List<Entity> 創建 List<GroupEntity>?
慕田峪4524236
2023-04-26 16:10:26