[英]Transform List of object to a Map in java
I have a list of item List<Item> resultBl
like below :我有一个项目
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
I want to transform this list to a map
with this form, the key is the id
and the value is a list
of objects :我想将此列表转换为具有这种形式的
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]], ...
I tried with different ways but always I had repeated elements:我尝试了不同的方法,但总是有重复的元素:
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);
}
downstream
Collectors.groupingBy
和Collectors.mapping
应该可以工作:
Map<Integer, List<ItemDetails>> result = resultBl.stream().collect(Collectors.groupingBy(Item::getId, Collectors.mapping(ItemDetails::new, Collectors.toList())));
I would use streams and groupingBy
to do this.我会使用流和
groupingBy
来做到这一点。
When you have a list of your items resultBl
all you have to do is当你有你的物品清单
resultBl
你所要做的就是
Map<Integer, List<Item>> resultMap = resultBl.stream().collect(groupingBy(Item::getId, toList()));
imports:进口:
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
This will group your items by the id
parameter.这将按
id
参数对您的项目进行分组。
Your best option would be to add a constructor to ItemDetails
accepting an Item
object:您最好的选择是向
ItemDetails
添加一个接受Item
对象的构造函数:
public class ItemDetails {
// properties, getters and setters
public ItemDetails(Item item) {
this.amount = item.getAmount();
this.nameType = item.getNameType();
}
}
And then use the following Java 8 features:然后使用以下 Java 8 功能:
Map<Integer, List<ItemDetails>> itemsPerId =
itemsList.stream().collect(Collectors.groupingBy(Item::getId, Collectors.mapping(ItemDetails::new, Collectors.toList())));
Map<Integer,List<Item>> map = resultBL.stream(Collectors.toMap(Item::getId, Function.identity()));
It is Lambda.它是拉姆达。 Java version >= 8
Java 版本 >= 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.