Search code examples
javacsvhashmap

Java: pass from CSV into HashMap and Print Key and values


I have a CSV file with 5 rows, and three pieces of data separated by comas on each row. Row Example: Drew, 37, 150.5 I am trying to read the data from the CSV, into a HashMap and then print out the HashMap Keys and Values. Right now I'm only getting empty brackets to print out. Code below, I'm taking an online course and having trouble reaching the professor, and have tried several online resources, appreciate anyone's advice so I can learn. TY!

import java.io.FileNotFoundException;  // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
import java.util.HashMap;
import java.util.Map;

public class Main {
  public static void main(String[] args) {
    Map<String, Person> myPeople = new HashMap();
    try {
      File myObj = new File("people.csv");
      Scanner myReader = new Scanner(myObj);
      while (myReader.hasNextLine()) {
        String data = myReader.nextLine();
        
        System.out.println(myPeople);
      }
      myReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}```
My current output is below, without keys or values.
 java -classpath .:/run_dir/junit-4.12.jar:target/dependency/* Main
{}
{}
{}
{}
{}
 

Solution

  • You haven't added anything to your map, that's why it is just printing empty map ({}) on each iteration. Here is an example of how to do this:

    public class Main {
    
        static class Person {
            String name;
            int age;
            int height;
    
            public Person(String name, int age, int height) {
                this.name = name;
                this.age = age;
                this.height = height;
            }
    
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (o == null || getClass() != o.getClass()) return false;
                Person person = (Person) o;
                return age == person.age && height == person.height && name.equals(person.name);
            }
    
            @Override
            public int hashCode() {
                return Objects.hash(name, age, height);
            }
    
            @Override
            public String toString() {
                return "Person{" +
                        "name='" + name + '\'' +
                        ", age=" + age +
                        ", height=" + height +
                        '}';
            }
        }
    
        private static final String csv =
                "Drew, 37, 168\n" +
                        "Bob, 30, 170";
    
        public static void main(String[] args) {
            Map<String, Person> map = new HashMap<>();
            try (Scanner scanner = new Scanner(csv)) {
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    String[] lineParts = line.split("\\s*,\\s*");
                    map.put(lineParts[0], new Person(lineParts[0], Integer.parseInt(lineParts[1]), Integer.parseInt(lineParts[2])));
                }
            }
            System.out.println(map);
        }
    }
    

    Output: {Bob=Person{name='Bob', age=30, height=170}, Jack=Person{name='Jack', age=37, height=168}}