Reputation: 7788
I'm trying to sync to user list by building a map that contains a username as a key and an user object as the value. Once the map has been built, I'm having difficulties retrieving the object values. Below is the code I'm using.
private Map<String, User> map = new HashMap<String, User>();
I'm populating the map key and object as followed.
List<User> users = session.createCriteria(User.class).list();
for(ApplicationUser user : users) {
map.put(user.getUserName(), user);
}
I'm trying to retrieve the data as followed,
List<Person> persons = session.createCriteria(Person.class).list();
for (Person p : persons) {
User user = map.containsKey(p.getUsername()) ? map.get(p.getUsername()) : new User();
//Email is always null.
System.out.println(user.getEmail());
}
Could someone help point me in the right direction on how to retrieve the object values from my map. Thanks
Upvotes: 1
Views: 3729
Reputation: 275
@George I think you will get a nullpointer exception if the user doesn't belong to person.
System.out.println(user.getEmail());
when condition is false User user = new User(); user.getEmail() is null
Upvotes: -1
Reputation: 1538
It seems like email is null because you are not initialising email in the default constructor of User() which gets executed here :
User user = map.containsKey(p.getUsername()) ? map.get(p.getUsername()) : new User();
Here , i think the usernames that you put in the map does not match with those you try to retrieve in the second part of the code . i.e . map.containsKey(p.getUsername()) seems to return false and default constructor gets called with email as null .
Try printing out the(or debug inspect) the map keyset() and the person usernames and check if they match exactly .
Upvotes: 0
Reputation: 39651
First, you should change your loop to this:
for (Person p : persons) {
String username = p.getUsername();
User user = map.get(username);
if (user != null) {
System.out.println(user.getEmail());
} else {
System.out.println("User " + username + " is unknown");
}
}
Then set a breakpoint in the loop and debug your code. It looks correct so far. Maybe you are just not setting email
in User
or the users from persons
are not in your map
.
Upvotes: 4