簡體   English   中英

在java中將對象列表轉換為地圖

[英]Transform List of object to a Map in java

我有一個項目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);
}

downstream Collectors.groupingByCollectors.mapping應該可以工作:

Map<Integer, List<ItemDetails>> result = resultBl.stream().collect(Collectors.groupingBy(Item::getId, Collectors.mapping(ItemDetails::new, Collectors.toList())));

我會使用流和groupingBy來做到這一點。

當你有你的物品清單resultBl你所要做的就是

Map<Integer, List<Item>> resultMap = resultBl.stream().collect(groupingBy(Item::getId, toList()));

進口:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

這將按id參數對您的項目進行分組。

您最好的選擇是向ItemDetails添加一個接受Item對象的構造函數:

public class ItemDetails {

    // properties, getters and setters

    public ItemDetails(Item item) {
        this.amount = item.getAmount();
        this.nameType = item.getNameType();
    }

}

然后使用以下 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()));

它是拉姆達。 Java 版本 >= 8

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM