【发布时间】:2021-12-22 03:00:51
【问题描述】:
我有一个项目列表List<Item> resultBl,如下所示:
id = 18003 amount = 128 nameType = SUBMITTED
id = 18189 amount = 95 nameType = SUBMITTED
id = 18192 amount = 160 nameType = POSITIVE
id = 18192 amount = 30 nameType = DRAFT
id = 18192 amount = 873 nameType = SUBMITTED
id = 18237 amount = 390 nameType = POSITIVE
id = 18237 amount = 60 nameType = DRAFT
id = 18237 amount = 2731 nameType = SUBMITTED
我想用这种形式将此列表转换为map,键是id,值是对象的list:
Map<Integer,List<ItemDetails>> mapTest= new HashMap<Integer,List<ItemDetails>>();
[18237 , [amount = 390 ,nameType = POSITIVE],[amount = 60 nameType = DRAFT], [amount = 2731 nameType = SUBMITTED]], ...
我尝试了不同的方法,但总是有重复的元素:
List<Integer> ids2 = new ArrayList<Integer>();
List<Integer> ids = new ArrayList<Integer>();
for(Item item: resultBl) {
ids.add(item.getId());
}
ids2 =ids.stream().distinct().collect(Collectors.toList());
Map<Integer,List<ItemDetails>> mapTest= new HashMap<Integer,List<ItemDetails>>();
List<ItemDetails> itemDetailsList = new ArrayList<ItemDetails>();
for(Integer s:ids2) {
for(Item i : resultBl) {
if(s.equals(i.getId())) {
ItemDetails it =new ItemDetails();
it.setAmount(i.getAmount());
it.setNameType(i.getNameType()) ;
itemDetailsList .add(it);
}
}
mapTest.put(s, itemDetailsList);
}
【问题讨论】: