pojo类中list存储其他字段_Java 将List中的实体类按照某个字段进行分组并存放至Map中操作...

1、JDK1.8之前:

假设有实体类User,里面有字段id,我们将相同id的User进行分组,并存放在Map中。(例子不是很恰当,但很能说明问题)

public static void main(String[] args) {

List list = new ArrayList<>();

list.add(new User(1, 1));

list.add(new User(1, 2));

list.add(new User(2, 1));

list.add(new User(2, 3));

list.add(new User(2, 2));

list.add(new User(3, 1));

Map> map = new HashMap<>();

for(User user : list){

if(map.containsKey(user.getId())){//map中存在此id,将数据存放当前key的map中

map.get(user.getId()).add(user);

}else{//map中不存在,新建key,用来存放数据

List tmpList = new ArrayList<>();

tmpList.add(user);

map.put(user.getId(), tmpList);

}

}

System.out.println(map.toString());

}

执行结果:

可以看到达到了了我们的目的

2、JDK1.8 新特性实现

Map> map = list.stream().collect(Collectors.groupingBy(User::getId));

附上

List>>分组

List>> list = new ArrayList<>();

Map>> contractIdMap =

list.stream().collect(Collectors.groupingBy(m -> (Long.parseLong(m.get("contractId").toString()))));

Map>> nameMap =

list.stream().collect(Collectors.groupingBy(m -> (m.get("name").toString())));

补充知识:java中对list的数据按照某个属性进行分组,拆分成多个list

我就废话不多说了,大家还是直接看代码吧~

/**

* 按照List>里面map的某个value重新封装成多个不同的list, 原始数据类型List

* >, 转换后数据类型Map>>

*

* @param list

* @param oneMapKey

* @return

*/

private static Map change(List> list, String oneMapKey) {

Map resultMap = new HashMap();

Set setTmp = new HashSet();

for (Map tmp : list) {

setTmp.add(tmp.get(oneMapKey));

}

Iterator it = setTmp.iterator();

while (it.hasNext()) {

String oneSetTmpStr = (String) it.next();

List> oneSetTmpList = new ArrayList>();

for (Map tmp : list) {

String oneMapValueStr = (String) tmp.get(oneMapKey);

if (oneMapValueStr.equals(oneSetTmpStr)) {

oneSetTmpList.add(tmp);

}

}

resultMap.put(oneSetTmpStr, oneSetTmpList);

}

return resultMap;

}

以上这篇Java 将List中的实体类按照某个字段进行分组并存放至Map中操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值