Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array of hashmaps

In python, I’d use a list of dictionaries to collect data (like name, age, height, etc.) of several people that a user enters, but now I want to do the same thing in Java. Is an array of HashMaps the best way to do that?

static List<Map<String, Object>> driverList = new ArrayList<>();

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You could do that, but a more idiomatic approach for Java would be to create a Person class that contains all the data members you want to collect. E.g.:

public class Person {
    private String name;
    private int age;
    // other properties...

    // Constructor using these properties
    // Note: this is a stylistic choice. Some would prefer a default ctor and using setters later
    public Person (String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters and setters for all the properties

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int numPeople = 7; // Arbitrary number for the example
        List<Person> people = new ArrayList<>(numPeople);
        for (int i = 0; i < numPeople; ++i) {
            System.out.print("Name: ");
            String name = sc.nextString();
            System.out.print("Age: ");
            int age = sc.nextInt();
            people.add(new Person(name, age));
        }
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading