Home > Enterprise >  Store user Data in a Hashmap
Store user Data in a Hashmap

Time:04-01

I have created a form which will collect user data, store it in a HashMap and print the HashMap in the console. I have tried all ways I could think of but they are not working. Here is what I've tried so far.

//This is the class will store user data in a hashmap

public class userRegistrationData {

HashMap<String, ArrayList<String>> userData;

public userRegistrationData() {
    RegistrationForm form = new RegistrationForm();
    userData = new HashMap<String,ArrayList<String>>();
    
    String id = String.valueOf(form.getUserIdField());
    String firstName = String.valueOf(form.getFirstNameTextField());
    String lastName = String.valueOf(form.getLastNameTextField());
    String phone = String.valueOf(form.getPhoneTextField());
    String city = String.valueOf(form.getCityTextField());
    String createPassword = String.valueOf(form.getCreatePasswordField());
    String confirmPassword = String.valueOf(form.getConfirmPasswordField());
    
    userData.put(id, new ArrayList<String>());
    userData.get(id).add(id);
    userData.get(id).add(firstName);
    userData.get(id).add(lastName);
    userData.get(id).add(lastName);
    userData.get(id).add(phone);
    userData.get(id).add(city);
    userData.get(id).add(createPassword);
    userData.get(id).add(confirmPassword);
}
private HashMap<String, ArrayList<String>> formData() {
    return userData;    
}
public HashMap<String, ArrayList<String>> getUserData() {
    return userData;
}
public void setUserData(HashMap<String, ArrayList<String>> userData) {
    this.userData = userData;
}

} //The action perfomed method which will listen to the submit button

@Override
public void actionPerformed(ActionEvent e) {
    userRegistrationData data = new userRegistrationData();
    if(e.getSource().equals(submitBtn)) {
        if(data.getUserData().containsKey(getUserIdField())) {
            System.out.println(data.getUserData());
        }
    }
    
    
}

CodePudding user response:

you can print it by this simple code:

data.getUserData().entrySet().forEach(entry -> {
System.out.println(entry.getKey()   "\n"   
Arrays.deepToString(entry.getValue().toArray()));
});

CodePudding user response:

Add a toString function in userRegistrationData class:

public void toString(String id) {
        System.out.println(userData.get(id));
}

In your actionPerformed function, simply call

data.toString(String.toValue(getUserIdField()));

Instead of printing the object in toString function, you can also return it to the actionPerformed function as String.

  • Related