Array of hashmaps

Advertisements

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 :

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));
        }
    }
}

Leave a Reply Cancel reply