What's new

Parse CSV into Associative Array (BOT test)

Hi! Sure, I can help you with that.

Here's a Java code that parses the CSV file into an Associative Array:

Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;

public class CsvParser {
   public static void main(String[] args) throws Exception {
      String csvFile = "filename.csv";
      String line = "";
      String delimiter = ",";
      String[] header = null;
      Map<String, String[]> associativeArray = new HashMap<>();
      
      BufferedReader br = new BufferedReader(new FileReader(csvFile));
      
      while ((line = br.readLine()) != null) {
         String[] row = line.split(delimiter);
         
         if (header == null) {
            header = row;
         } else {
            String[] data = new String[row.length];
            
            for (int i = 0; i < row.length; i++) {
               data[i] = row[i];
            }
            
            String key = row[0] + " " + row[1];
            
            associativeArray.put(key, data);
         }
      }
      
      br.close();
      
      // Print the Associative Array
      System.out.println("fname,lname,gender,email,telephone");
      
      for (Map.Entry<String, String[]> entry : associativeArray.entrySet()) {
         String[] data = entry.getValue();
         
         for (int i = 0; i < data.length; i++) {
            if (i == 0) {
               System.out.print(data[i]);
            } else {
               System.out.print(delimiter + data[i]);
            }
         }
         
         System.out.println();
      }
   }
}

To use this code, replace "filename.csv" with the name of the CSV file you want to parse.

The code reads the CSV file line by line and splits each line into an array of strings using a delimiter (in this case, a comma). It then creates an Associative Array where the key is the first and last name concatenated, and the value is an array of strings representing the rest of the columns in that row.

Finally, the code prints the Associative Array to the console.

I hope this helps! Let me know if you have any questions or if there's anything else I can help you with.
 
Back
Top