• Home
  • Java pass from csv into hashmap and print key and values

Java pass from csv into hashmap and print key and values

To pass data from a CSV file into a HashMap in Java and print the keys and values, you can use the following steps:

  1. First, create a BufferedReader object to read the CSV file. You can do this by opening a FileReader object on the file and passing it to the BufferedReader constructor.
  2. Create a HashMap object to store the data from the CSV file. You can do this by declaring a new HashMap object and specifying the key and value types as the generic parameters.
  3. Read the first line of the CSV file using the BufferedReader’s readLine() method. This line should contain the column headers, which you can use as the keys in the HashMap.
  4. Split the first line into an array of strings using the String.split() method and a suitable delimiter (e.g., a comma).
  5. Iterate through the array of column headers, adding each one as a key in the HashMap with an initial value of null.
  6. Read the rest of the lines in the CSV file using a loop and the BufferedReader’s readLine() method. For each line, split it into an array of strings using the String.split() method and the same delimiter as before.
  7. Iterate through the array of values, using the corresponding column header as the key and the current value as the value in the HashMap.
  8. After all lines have been read, the HashMap should contain all the data from the CSV file. You can iterate through the HashMap and print the keys and values using its entrySet() method and a suitable loop.

Here is an example of code that performs these steps:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CSVToHashMap {
public static void main(String[] args) {
// File path of the CSV file
String filePath = "data.csv";

// Delimiter used in the CSV file
String delimiter = ",";

// Map to store the data from the CSV file
HashMap<String, String> map = new HashMap<>();

try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
// Read the first line (column headers)
String line = reader.readLine();
if (line != null) {
// Split the line into an array of strings
String[] headers = line.split(delimiter);
// Add each header as a key in the map with a null value
for (String header : headers) {
map.put(header, null);
}
}

// Read the rest of the lines
while ((line = reader.readLine()) != null) {
// Split the line into an array of strings
String[] values = line.split(delimiter);
// Iterate through the array and add the values to the map
int i = 0;
for (String value : values) {
String key = (String) map.keySet().toArray()[i];
map.put(key, value);
i++;
}
}
} catch (IOException e) {
e.printStackTrace