Convert CSV values to a HashMap key value pairs in JAVA

前端 未结 8 1010
刺人心
刺人心 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:14

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.*;
    public class Example {
    
    
        public static void main(String[] args) {
    
            String csvFile = "test.csv";
            String line = "";
            String cvsSplitBy = ",";
            HashMap list = new HashMap<>();
            try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
    
                while ((line = br.readLine()) != null) {
    
                    // use comma as separator
                    String[] country = line.split(cvsSplitBy);
    
                    //System.out.println(country[0] +"  "  + country[1]);
                    list.put(country[0], country[1]);
                }
    
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(list);
    
        }
       // enter code here
    
    }
    

提交回复
热议问题