简体   繁体   English

Java:从 CSV 传递到 HashMap 并打印键和值

[英]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.我有一个 CSV 文件,它有 5 行,每行有 3 条数据,用逗号分隔。 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.行示例:Drew, 37, 150.5 我正在尝试将 CSV 中的数据读取到 HashMap 中,然后打印出 Z063A5BC470661C3C7909BCE1B7E971A5 键和值。 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
{}
{}
{}
{}
{}
 

You should be printing data rather than myPeople, as you have not added anything to myPeople yet.您应该打印数据而不是 myPeople,因为您还没有向 myPeople 添加任何内容。

You can use myPeople.put(key, value) to add elements to your map, see https://www.geeksforgeeks.org/hashmap-put-method-in-java/ .您可以使用 myPeople.put(key, value) 将元素添加到 map,请参阅https://www.geeksforgeeks.org/hashmap-put-method-in-java/

Then you can use myPeople.get(key) to retrieve the value, see https://www.geeksforgeeks.org/java-util-hashmap-in-java-with-examples/ .然后您可以使用 myPeople.get(key) 检索该值,请参阅https://www.geeksforgeeks.org/java-util-hashmap-in-java-with-examples/

You haven't added anything to your map, that's why it is just printing empty map ({}) on each iteration.您没有向 map 添加任何内容,这就是为什么它在每次迭代时只打印空的 map ({})。 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}} Output: {Bob=Person{name='Bob', age=30, height=170}, Jack=Person{name='Jack', age=37, height=168}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM