亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用流從 List<Entity> 創建 List<GroupEntity>?

如何使用流從 List<Entity> 創建 List<GroupEntity>?

慕田峪4524236 2023-04-26 16:10:26
我收到一個實體列表,我需要將它們按 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 對象。是否可以?
查看完整描述

2 回答

?
烙印99

TA貢獻1829條經驗 獲得超13個贊

假設實現and ,您首先構建,然后EntityPK將其映射到.equalshashCodeMap<EntityPK, List<Entity>>List<GroupOfEntity>

假設 GroupOfEntity有合適的構造函數,你會這樣做:

List<GroupOfEntity> groupEntities = listOfEntities.stream()
        .collect(Collectors.groupingBy(Entity::getEntityPk))
        .entrySet().stream()
        .map(e -> new GroupOfEntity(e.getKey().getPeriodMonth(),
                                    e.getKey().getPeriodYear(),
                                    e.getValue()))
        .collect(Collectors.toList());


查看完整回答
反對 回復 2023-04-26
?
白衣染霜花

TA貢獻1796條經驗 獲得超10個贊

首先,這樣做:

?Map<EntityPK,?List<Entity>>?groupEntities?=
?entities.stream().collect(Collectors.groupingBy(Entity::getEntityPk));

然后從上面的地圖創建 GroupOfEntity。這兩個步驟也可以結合起來。

stream這是進一步映射和創建的組合步驟GroupOfEntity

List<GroupOfEntity>?groupEntities
????????=?entities.stream().collect(Collectors.groupingBy(Entity::getEntityPk)).entrySet()
????????.stream().map(e?->?new?GroupOfEntity(e.getKey().getPeriodMonth(),?e.getKey().getPeriodYear(),?e.getValue()))
????????.collect(Collectors.toList());
查看完整回答
反對 回復 2023-04-26
  • 2 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號