list的lambda遍历转换List<Object>为Map<key, List<Object>>

原创
06/23 17:14
阅读数 17
public class AccountBadgeDemo{
	public static void main(String[] args) {
        AccountBadge accountBadge = new AccountBadge();
        accountBadge.setBadgeName("111111");
        accountBadge.setCategoryId(1l);
        AccountBadge accountBadge1 = new AccountBadge();
        accountBadge1.setBadgeName("222222");
        accountBadge1.setCategoryId(1l);
        AccountBadge accountBadge2 = new AccountBadge();
        accountBadge2.setBadgeName("222222");
        accountBadge2.setCategoryId(2l);
        AccountBadge accountBadge3 = new AccountBadge();
        accountBadge3.setBadgeName("222222");
        accountBadge3.setCategoryId(3l);
        List<AccountBadge> badgeList = new ArrayList<>();
        badgeList.add(accountBadge);
        badgeList.add(accountBadge1);
        badgeList.add(accountBadge2);
        badgeList.add(accountBadge3);
        Map<Long, List<AccountBadge>> accountBadgeMap = new HashMap<>();
        badgeList.stream().forEach(accountBadgeTemp -> {
            List<AccountBadge> accountBadgeList = accountBadgeMap.get(accountBadgeTemp.getCategoryId());
            if(CollectionUtils.isEmpty(accountBadgeList)){
                accountBadgeList = new ArrayList<>();
            }
            accountBadgeList.add(accountBadgeTemp);
            accountBadgeMap.put(accountBadgeTemp.getCategoryId(), accountBadgeList);
        });
        System.out.println(JSONObject.toJSONString(accountBadgeMap));
    }
}

@Data
public class AccountBadge implements Serializable {

    private static final long serialVersionUID = 1L;
    // 分类ID
    private Long categoryId;
    // 徽章名称
    private String badgeName;

}

展开阅读全文
加载中

作者的其它热门文章

打赏
0
0 收藏
分享
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部
返回顶部
顶部