Reputation: 14864
In JavaScript I can define the following collection with keys awaiting values
var items = {
'book':null,
'pen':null,
'pencil':null,
'chicken':null,
'wallet':null
};
Then when I am ready to add values to my collection, I can do for instance
for(var p in items){
if(some condition){
items[p]=someValue;
}
}
Is there a way to do this with the same level of efficiency in java?
I know that in old Java I can combine a Map and a List to accomplish this, but are their new data structures in Java that can handle this? I am talking about Java 7 (or 8) perhaps? I am using Google App-Engine for my Java.
Upvotes: 2
Views: 89
Reputation: 5932
EDIT: Updated my answer based on the latest comments.
You could perfectly use a HashMap to achieve the same effect. To iterate over the existing keys, use the Map#keySet
method.
Map<String, String> map = new HashMap<String, String>();
map.put("book", null);
map.put("pen", null);
for (String key : map.keySet()) {
map.put(key, "Some Value");
}
System.out.println(map);
Upvotes: 4
Reputation: 122006
You could try it this way, if you're looking for the same style.
HashMap<String, String > items = new HashMap<String, String>(){{
put("book",null);
put("pen",null);
}};
Later you can put again with keys.
items.put("book", "Some Bible");
It seems you are new to Java and both Collections. I'm highly recommend you to read the about HashMap more before proceeding.
Upvotes: 6