I have a list of usernames and one of nodes. I need a data structure to hold information about what usernames are on a given node. I would need something like HashMap<String, ArrayList<String> but I also need to perform operation on the whole username list in an easy (not on a bunch of different arrays). Does that data structure exists or I need to hold twoArrayList and an HashMap?
- 5,917
- 4
- 41
- 56
- 131
- 1
- 11
4 Answers
HashMap<String, ArrayList<String> seems like a reasonable solution to me. I don't see any need for custom structures here.
For the operations with usernames, you can use .keySet() or .entrySet() (or any method of iteration).
- 5,917
- 4
- 41
- 56
I like your original thought about using a Map. I think a Map would be a good start for this problem.
Are all the usernames guaranteed to be unique? If so, I would use a Set instead of a List to represent the usernames. Maybe you could first transfer all usernames in the list to a Set<Usernames>, then you could iterate through the node/username lists to generate your Map<Node, Set<Usernames>>.
You would to keep track of the Set<Usernames> and a Map<Node, Set<Usernames>>, but I think it would store the right data and you could do fast lookup operations on the username set.
- 35
- 1
- 7
If something doesn't exist in Java you can try to create on your own:
Node:
public class Node {
List<User> users = new ArrayList<>();
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
User:
public class User {
String username;
String name;
String surname;
// ...
}
You can just use List<String> usernames in your Node, if you don't need a complex object.
Then, somewhere in your app:
public List<User> getUsersOfNode(Node node) {
return node.getUsers();
}
Operating with this is easier than with HashMap.
- 6,457
- 10
- 40
- 58
Why don't you create an object for that, with 3 private fields (two lists and one map)?
- 92
- 1
- 4