学习 Java 并已经弄清楚如何在数组中存储 HashMap 。但我不知道如何获取存储的数据。这是我正在做的事情的简化版本。我已经显示了特定的数组项,但是如何访问存储在数组中的 HashMap ?
import java.util.*;
public class HelloWorld {
public static void main(String[] args) {
Map<String, String> custOrder = new HashMap<String, String>();
List ordersPlaced = new ArrayList();
custOrder.put("colour", "blue");
custOrder.put("manu", "bmw");
custOrder.put("body", "4x4");
ordersPlaced.add(custOrder);
custOrder = new HashMap();
custOrder.put("colour", "green");
custOrder.put("manu", "merc");
custOrder.put("body", "saloon");
ordersPlaced.add(custOrder);
System.out.println(ordersPlaced.get(0).toString());
}
}
希望这是有道理的。提前致谢
尼尔
最佳答案
您已经在访问它。
为了获取 map 项目的迭代,您可以:
ordersPlaced.get(0).forEach((key, value) -> {
System.out.println("Key is: " + key + ", Value is: " + value);
});
或者,在 Java 8 之前,类似:
for (Map.Entry<String, String> entry : ordersPlaced.get(0).entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
}
请注意,您应该避免使用原始类型列表。相反,您应该:
List<Map<String, String>> ordersPlaced = new ArrayList<>();
然后:
Map<String, String> m = ordersPlaced.get(0);
关于Java 如何访问数组中保存的 HashMap 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48609437/