Convert CSV values to a HashMap key value pairs in JAVA

前端 未结 8 1001
刺人心
刺人心 2020-12-03 03:33

HI I have a csv called test.csv . I am trying to read the csv line by line and convert the values into a hash key value pairs . Here is the code :-



        
相关标签:
8条回答
  • 2020-12-03 04:36

    Using FasterXML's CSV package: https://github.com/FasterXML/jackson-dataformats-text/tree/master/csv

    public static List<Map<String, String>> read(File file) throws JsonProcessingException, IOException {
        List<Map<String, String>> response = new LinkedList<Map<String, String>>();
        CsvMapper mapper = new CsvMapper();
        CsvSchema schema = CsvSchema.emptySchema().withHeader();
        MappingIterator<Map<String, String>> iterator = mapper.reader(Map.class)
                .with(schema)
                .readValues(file);
        while (iterator.hasNext()) {
            response.add(iterator.next());
        }
        return response;
    }
    
    0 讨论(0)
  • 2020-12-03 04:36

    The problem is that when you split your str, the first element in each line is alone (i.e 1 and 2). So arr only contains ["1"], and hence arr[1] doesn't exists.

    I.e for the example input :

    1,"testCaseName":"ACLTest"
    

    split by , => str contains {1, testCaseName:ACLTest}
    split by : at the first iteration => arr contains {1}

    Example :

    String s = "1,testCaseName:ACLTest";
    String str[] = s.split(",");
    System.out.println(Arrays.toString(str));
    for(String p : str){
        String arr[] = p.split(":");
        System.out.println(Arrays.toString(arr));
    }
    

    Output :

    [1, testCaseName:ACLTest]
    [1] //<- here arr[1] doesn't exists, you only have arr[0] and hence the ArrayIndexOutOfBoundsException when trying to access arr[1]
    [testCaseName, ACLTest]
    


    To fix your code (if you don't want to use a CSV parser), make your loop starting at 1 :

    for(int i=1;i<str.length;i++){
          String arr[] = str[i].split(":");
          map.put(arr[0], arr[1]);
    }
    


    Another problem is that the HashMap use the hashCode of the keys to store the (key, value) pairs.

    So when insering "testCaseName":"ACLTest" and "testCaseName":"DCLAddTest", the first value will be erased and replace by the second one :

    Map<String, String> map = new HashMap<>();
    map.put("testCaseName","ACLTest");
    map.put("testCaseName","DCLAddTest");
    System.out.println(map);
    

    Output :

    {testCaseName=DCLAddTest}
    

    So you have to fix that too.

    0 讨论(0)
提交回复
热议问题