遍历数组列表的哈希图

时间:2018-09-21 18:28:43

标签: java arraylist hashmap

我有一个csv文件,其中包含数据,我想解析所有用逗号分隔的数据,我已经完成了从文件中读取数据的代码。

我该如何浏览数据?

这是我的代码:

    ArrayList<String> keys;             // Holds key names from header row
    ArrayList<String> values;           // Holds the values read from subsequent rows

    HashMap<String, String> row;        // Holds the key/value pairs for each data row

    String line, header;


    ArrayList data = new ArrayList<>(); // Create ArrayList to hold HashMaps for all rows

    try {


        Scanner in = new Scanner(Paths.get("myfile.csv"), "UTF-8");

        /* Get list of keys from the header row; split into an ArrayList */

        header = in.nextLine();
        keys = new ArrayList(Arrays.asList(header.split(",")));

        /* Read and process every subsequent row (record) in CSV file */

        while ( in.hasNextLine() ) {

            /* Get next line */

            line = in.nextLine();

            /* Create new map for current row */

            row = new HashMap<>();

            /* Split comma-separated values into ArrayList */

            values = new ArrayList(Arrays.asList(line.split(",")));

            /* Populate map, using key names from the header row */

            for (int i = 0; i < keys.size(); i++) {

                row.put(keys.get(i), values.get(i));

            }

            /* Add map to data container */

            data.add(row);

        }

         in.close();

          // HERE I want to loop through data and display all key values
          // How am I going to do it?
          // the csv contains columns: firstname lastname city address
         }

    catch (Exception e) {

        System.err.println(e.toString());

    }

任何人都可以帮助您遍历数据吗?

1 个答案:

答案 0 :(得分:0)

首先,更改您的Arraylist类型,以避免一直转换。就是说这样data ArrayList;

ArrayList<HashMap<String, String>> data = new ArrayList<>();

,然后将您的打印区域添加到此Stream代码中。我添加了注释以便清楚理解。

//loop on data list
data.forEach(hashMapOfRows -> {
    //seperate all data to read carefully,you can modify to your wants
    System.out.println("------------------");
    //for iteratable element is hashmap. So iterate on key value pair and print
    hashMapOfRows.forEach((key, value) -> System.out.print(key + ":" + value + ","));
    //seperate between elements.
    System.out.println();
    System.out.println("------------------");
});