如何将List <string []>放入Map <string,list <string =“”>&gt;

时间:2018-01-17 09:01:47

标签: java logic

enter image description here

这是我的List<String[]>对象,我必须放入一个hashmap - Map<String, List<String>>。 第一个字符串数组是我的键。 我必须按顺序放置其他数组 - First Row = First Key,Second Row = Second key ecc ..

我试过写一个算法,但不知道如何完成

    public Map<String, List<String>> getMapWithListOfStrings() throws IOException {
    Map<String, List<String>> returningMap = new HashMap<>();
    List<String[]> readAll = csvReader.readAll();
    for (int i = 0; i < 1; i++) {
        for (String get : readAll.get(i)) {
            returningMap.put(get, new ArrayList<String>());
        }
    }
    for (int i = 0; i < returningMap.size(); i++) {
    }
    return returningMap;
}

2 个答案:

答案 0 :(得分:1)

这是你需要的吗?

public Map<String, List<String>> getMapWithListOfStrings() {
    Map<String, List<String>> returningMap = new HashMap<>();
    List<String[]> readAll = csvReader.readAll();
    String[] keys = readAll.get(0);
    for (int i = 0; i < keys.length; i++) {
        String key = keys[i];
        List<String> value = new ArrayList<>();
        // j = 0 is excluded - it contains the keys, not the values
        for(int j = 1; j < readAll.size(); j++) {
            String iValue = readAll.get(j)[i];
            value.add(iValue);
        }
        returningMap.put(key, value);
    }
    return returningMap;
}

答案 1 :(得分:1)

我不确定我是否完全理解您的问题,但我想以下(代码未经测试)应该可以解决您的问题。

String[] keys = readAll.get(0);

// Make sure there is one key per line of data.
if(keys.length!=readAll.size()-1) {
    throw new IllegalStateException("Invalid CSV format!");
}

// Put all the data lines together with their respective key into your Map.
for(int i=1;i<readAll.size();i++) {
    returningMap.put(keys[i-1],Arrays.asList(readAll.get(i)));
}