Java新手,很奇怪是否有办法让HashMap的值为字符串或ArrayList:
HashMap<String, HashMap<String, ArrayList<String>>> map = new HashMap<String, HashMap<String, ArrayList<String>>>();
map.putIfAbsent("238991", new HashMap<String, ArrayList<String>>());
map.get("238991").put("OrderID", new ArrayList<>());
map.get("238991").get("OrderID").add("1234H");
map.get("238991").get("OrderID").add("1233B");
map.get("238991").put("Name", new ArrayList<>());
map.get("238991").get("Name").add("Smith, John");
System.out.println(map.get("238991"));
System.out.println(map.get("238991").get("Name").get(0));
如果我可以为Name而不是只访问列表的第一个元素,我宁愿只添加一个String。这可能吗?
答案 0 :(得分:2)
您应该创建一个POJO,并将其用作HashMap
值。它可以包含您需要的所有数据。在Java中编写“pythonic”代码同样糟糕,就像反过来一样。
答案 1 :(得分:0)
答案可能是否定的。
我说“可能”因为这个:
System.out.println(map.get("238991").get("Name").toString());
将打印:
[Smith, John]
这是有效的,因为ArrayList.toString()
方法将格式化列表。但是,这可能不是你想要的,因为:
如果列表中有多个元素,您将获得所有元素; e.g。
map.get("238991").get("Name").add("Jones, Barry");
[Smith, John, Jones, Barry]
答案 2 :(得分:0)
您应该使用POJO。 创建一个满足您需求的课程更加可行。
main.class
import java.util.ArrayList;
import java.util.HashMap;
public class OwnClass {
public static void main(String[] args) {
HashMap<String, Order> map = new HashMap<>();
ArrayList<String> orderItems = new ArrayList<>();
orderItems.add("1234H");
orderItems.add("1234B");
map.putIfAbsent("238991", new Order("Smith, John", orderItems));
map.get("238991").addOrder("1234J");
System.out.println(map);
}
}
Order.class
import java.util.ArrayList;
public class Order {
private String customer;
private ArrayList<String> items;
public Order(String string, ArrayList<String> orderItems) {
this.customer = string;
this.items = orderItems;
}
@Override
public String toString() {
return "Customer " + customer + " ordered " + items;
}
public void addOrder(String string) {
items.add(string);
}
}
输出:
{238991=Customer Smith, John ordered [1234H, 1234B, 1234J]}
答案 3 :(得分:0)
import java.util.*;
public class MapReceivesListOrString {
public static void main(String []args){
boolean shouldAddList = true;
Map<String, Object> map = new HashMap<String, Object>(); //Creating a HashMap Polymorphically
List<String> list = new ArrayList<>();
list.add("1234H");
list.add("1233B");
String code1 = "some code one";
String code2 = "some code two";
if (shouldAddList) { // Your business logic whether to add a list or a string
map.put("OrderID", list);
} else {
map.put("code1", code1);
map.put("code2", code2);
}
for (Map.Entry<String, Object> mapValues : map.entrySet()) { // Iterate over many list's or many string's
Object value = mapValues.getValue();
if (value instanceof List) {
ArrayList myList = (ArrayList) value;
System.out.println("List value one: " + list.get(0));
System.out.println("List value two: " + list.get(1));
} else {
System.out.println("String value: " + value.toString());
}
}
}
}
基于java泛型的存在,我们应该定义一个特定的类型,例如<String, ArrayList>
而不是<String, Object>
,但它是完全有效的语法。