Array/list of hashmap?
I am coming from the world of Perl programming and am unfamiliar with how one would create a list of hashes in Java.
In perl, creating a list of hashes is easy.
@rows = (
{ food=>'pizza'},
{ d开发者_运维技巧rink=>'coke'}
);
Reading it out is just as easy:
foreach my $row (@$rows){
print $row->{food};
print $row->{drink};
}
How would one accomplish something similar in Java? Either with just strings, or also with the possibility of objects as well?
The following is roughly equivalent to your Perl code.
List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
Map<String,String>> map1 = new HashMap<String,String>();
map1.put("food", "pizza");
Map<String,String>> map2 = new HashMap<String,String>();
map2.put("drink", "coke");
Collections.addAll(mapList, map1, map2);
...
for (Map<String,String> map : mapList) {
System.out.println("food is " + map.get("food"));
System.out.println("drink is " + map.get("drink"));
}
However, as you can see this is a lot more cumbersome than in Perl. Which brings me to the point that it is usually a better idea to do this kind of thing in Java using custom classes instead of associative arrays (e.g. Map
instances). Then you can write this as something like:
List<Diet> dietList = new ArrayList<Diet>();
Collections.addAll(dietList, new Diet("pizza", null), new Diet(null, "coke");
...
for (Diet diet : dietList) {
System.out.println("food is " + diet.getFood());
System.out.println("drink is " + diet.getDrink());
}
This approach (using a custom class) is generally more robust, more efficient, and gives you more readable code.
List<Map<String,String>> mapList = new ArrayList<HashMap<String,String>>()
Without code you've tried or more specification I can just provide an example of what you're looking for. Ask more specifics and I can provide more info.
To iterate over the list:
for (Map<String, String> map : mapList) {
String value = map.get("food");
}
Actually in java is quite long compared to perl :(
To create:
List<Map<String,String>> list = new ArrayList<Map<String,String>>();
Map value1 = new HashMap();
value1.put("foo", "pizza");
list.add(value1);
Map value2 = new HashMap();
value2.put("drink", "coke");
list.add(value2);
To read:
for (Map<String,String> element : list) {
// print keys and values
}
If you want something more dynamic and still have access to java libraries you can use something like groovy (or scala or clojure).
精彩评论