Re: [問題] 多對多關係如何優雅合併?

作者: fgh81113 (阿景)   2022-04-10 23:42:51
※ 引述《sssyoyo (柚子)》之銘言:
: 各位好,想請教是否有更好的寫法,主要針對stream的用法
: 標題可能描述的不太精確,問題簡化後模擬是這樣:
: 例如有"使用者"與"群組",他們是多對多關係,存在一張DB的中間表
: (一個使用者可以有多個群組身分,一個群組中也能存在多個使用者)
: 今天我查詢以"使用者"出發,要列出所屬的群組有哪些,返回JSON像這樣
: [
: {"userId":1,"groups":[1,2,3]},
: {"userId":2,"groups":[2,3]},
: {"userId":3,"groups":[3]}
: ]
: 我寫的方法 https://i.imgur.com/iqnKqPE.png
: ================
: 痛點在於我還需要多定義一個UserVo,感覺應該能直接拼出JSONObject
: 以及我總感覺Stream應該可以更優雅的做到,像是groupingBy、歸約之類
: 我這個寫的只要key(就是userId)已經存在,就需要clone一份既存的groups資料
: 一直new ArrayList<>好像也挺浪費資源的
: 想詢問是否有更好的寫法,還請不吝賜教,感謝!
Map<Integer, List<Integer>> userMap =
list.stream().collect(
Collectors.groupingBy(
user -> user.getUserId(),
Collectors.mapping(
user -> user.getGroup(),
Collectors.toList()
)
)
);
List<UserVo> result =
userMap.entrySet().stream()
.map(entry -> {
UserVo vo = new UserVo();
vo.setUserId(entry.getKey());
vo.setGroups(entry.getValue());
return vo;
})
.collect(Collectors.toList());
不想用UserVo那就用Map吧
List<Map<String, Object>> result =
userMap.entrySet().stream()
.map(entry -> {
Map<String, Object> map = new HashMap<>(2);
map.put("userId", entry.getKey());
map.put("groups", entry.getValue());
return map;
})
.collect(Collectors.toList());
作者: sssyoyo (柚子)   2022-04-16 13:35:00
謝謝! 學到了

Links booklink

Contact Us: admin [ a t ] ucptt.com