[英]Use Java 8 Streaming to convert List<Map> to Map<String,List<Map>>, using value as key
[英]How to convert a List into a Map using List as key in Java
我讀了一個包含四列的Excel表,並創建一個列表。 現在,我想使用前三列作為鍵,並使用最后一列作為值。 我曾問過類似的問題,但在所有這些問題中,都使用String或Integer作為鍵。
public class initial {
private int from;
private int to;
private int via;
private int cost;
//constructor
//set and get methods
//hashCode and equals methods
}
public class myTuple {
private int from;
private int to;
private int via;
}
//main function
//get the Excel Table as a list
ArrayList<initial> myList = new ArrayList<initial>();
for(int i= mySheet.getFirstRowNum()+1 ; i<= mySheet.getLastRowNum(); i++) {
initial e = new initial();
Row ro = mySheet.getRow(i);
for(int j = ro.getFirstCellNum(); j <= ro.getLastCellNum(); j++) {
Cell ce = ro.getCell(j);
switch(j) {
case 0:
e.setFrom((int) ce.getNumericCellValue());
break;
.....
case 3:
e.setCost((int) ce.getNumericCellValue());
break;
}
}
myList.add(e);
}
//Create map
Map<myTuple, Integer> myMap = new HashMap<>();
在這一點之后,我不知道如何進行。 我相信我應該使用類似的東西;
Map<myTuple, Integer> myMap= myList.stream().collectC(ollectors.toMap(myList:: , myList::));
如果有人可以幫助我,我將不勝感激。
另外,如果您認為有一種更有效的方法(例如,我讀取數據並將其解析為列表的方法,將列表轉換為地圖的方法),請告訴我。 即使這不是本問題的內容,但是如果我有更好的方法讀取多維表並將其解析為List,我也很樂意聽到。 將來,我將擁有更大的表和更多的列。 因此,我不太確定是否要使用switch語句遍歷每一列。
您可以在循環時創建地圖。
Tuple key = new Tuple(row.getNum(0), row.getNum(1), row.getNum(2));
List<Integer> value = new ArrayList<>();
for (int cell = 3; cell < row.getCount(); cell++) {
value.add(row.getNum(cell));
}
Map.put(key,value);
toMap收集器需要2個函數(1個創建鍵,1個創建值)。 您可以使用lambda(從源類型中提取相關字段):
Map<MyTuple, Integer> myMap = myList
.stream()
.collect(Collectors.toMap(
i -> new myTuple(i.from, i.to, i.via),
i -> i.cost
));
您的目標類型“ MyTuple”需要一個構造函數,等於和哈希碼。
這是一個例子:
class Tuple implements Comparable<Tuple> {
Object one;
Object two;
Object three;
public Tuple(final Object one, final Object two, final Object three) {
this.one = one;
this.two = two;
this.three = three;
}
@Override
public int compareTo(final Tuple that) {
// TODO: Do your comparison here for the fields one, two and three
return 0;
}
}
Map<Tuple, Object> mapKeyedByCompositeTuple = new HashMap<>();
// TODO: Inside your loop
for (int i = 10; i > 0; i--) {
Tuple key = new Tuple("cell-one-value-" + i, "cell-two-value-" + i, "cell-three-value-" + i);
mapKeyedByCompositeTuple.put(key, "cell-four-value-" + i);
}
System.out.println(mapKeyedByCompositeTuple);
希望能有所幫助,干杯,邁克爾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.