如何在Java中使用列表作为键将列表转换为地图

时间:2019-05-12 06:39:56

标签: java list hashmap

我阅读了一个包含四列的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语句遍历每一列。

3 个答案:

答案 0 :(得分:2)

您可以在循环时创建地图。

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);

答案 1 :(得分:1)

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”需要一个构造函数,等于值和哈希码。

答案 2 :(得分:-1)

这里是一个例子:

[{"remotePath":"/var/www/html/public","localPath":"/home/ltdev/path/to/my/app/public"}]

希望有帮助, 干杯, 迈克尔