如何将HashMap值添加到ArrayList中

时间:2013-02-08 13:16:13

标签: java arraylist hashmap

我有一个HashMap,我正在迭代:

for(HashMap<String, Integer> aString : value){
                System.out.println("key : " + key + " value : " + aString);

            }

我得到的结果为:

key : My Name value : {SKI=7, COR=13, IN=30}

现在我需要将`SKI,COR和IN分成3个不同的ArrayLists及其相应的值?怎么做?

4 个答案:

答案 0 :(得分:0)

如果您的数据始终是JSON,则可以像通常使用JSON一样对其进行解码:

ArrayList<Integer> array = new ArrayList<Integer>();
JSONArray json = new JSONArray(aString);
for (int i =0; i< json.length(); i++) {
    array.add(json.getInt(i));
}

答案 1 :(得分:0)

我不太确定你的hashmap包含什么,因为你的代码非常简短,但它几乎看起来像是给你hashmap的toString()。迭代哈希映射的最佳方法是:

    Map mp;
    .....
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pairs = (Map.Entry)it.next();
        System.out.println(pairs.getKey() + " = " + pairs.getValue());
        String key = pairs.getKey();
        String value = pairs.getValue();
        //Do something with the key/value pair
    }

但是如果你正确地遍历你的hashmap,那么下面是手动将该字符串解析为三个不同的arraylists的解决方案,这可能是最安全的方法。

ArrayList < String > ski = new ArrayList < String > ();
ArrayList < String > cor = new ArrayList < String > ();
ArrayList < String > in = new ArrayList < String > ();

for (HashMap < String, Integer > aString: value) {
    System.out.println("key : " + key + " value : " + aString);
    aString.replace("{", "");
    aString.replace("}", "");
    String[] items = aString.split(", ");
    for (String str: items) {
        if (str.contains("SKI")) {
            String skiPart = str.split("=");
            if (skiPart.length == 2) ski.add(skiPart[1]);
        }
        elseif(str.contains("COR")) {
            String corPart = str.split("=");
            if (corPart.length == 2) cor.add(corPart[1]);
        }
        elseif(str.contains("IN")) {
            String inPart = str.split("=");
            if (inPart.length == 2) in.add(inPart[1]);
        }
    }

}

答案 2 :(得分:0)

这是一个充满HashMaps的ArrayList(或List):

ArrayList<HashMap<String, Object>> userNotifications = new ArrayList<HashMap<String, Object>>();
int count = 0;

HashMap<String, Object> notificationItem = new HashMap<String, Object>();
notificationItem.put("key1", "value1");
notificationItem.put("key2", "value2");
userNotifications.add(count, notificationItem);
count++;

然后检索值:

ArrayList<HashMap<String, Object>> resultGetLast5PushNotificationsByUser = new ArrayList<HashMap<String, Object>>();

resultGetLast5PushNotificationsByUser = methodThatReturnsAnArrayList();
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(0);
String value1= item1.get("key1");
String value2= item1.get("key2");
HashMap<String, Object> item1= resultGetLast5PushNotificationsByUser.get(1);
String value1= item1.get("key1");
String value2= item1.get("key2");

答案 3 :(得分:0)

目前尚不清楚您的预期输出的形状。

三个这样的列表:

[7]
[13]
[30]

或从键到三个列表的映射,如下所示:

{ "SKI" -> [7]  }
{ "COR" -> [13] }
{ "IN"  -> [7]  }

不过,这里有一些选择:

选项1

// HashMap does not preserve order of entries
HashMap<String, Integer> map = new HashMap<>();
map.put("SKI", 7);
map.put("COR", 13);
map.put("IN", 30);

List<List<Integer>> listOfLists = map.values()
                                     .stream()
                                     .map(Collections::singletonList)
                                     .collect(Collectors.toList());

listOfLists.forEach(System.out::println);
Output:
[7]
[30]
[13]

选项2

// LinkedHashMap preserves order of entries
LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>();
map2.put("SKI", 7);
map2.put("COR", 13);
map2.put("IN", 30);

List<List<Integer>> listOfLists2 = map2.values()
                                       .stream()
                                       .map(Collections::singletonList)
                                       .collect(Collectors.toList());

listOfLists2.forEach(System.out::println);
Output:
[7]
[13]
[30]

选项3

HashMap<String, Integer> map3 = new HashMap<>();
map3.put("SKI", 7);
map3.put("COR", 13);
map3.put("IN", 30);

HashMap<String, List<Integer>> result = new HashMap<>();
map3.forEach((key, value) -> result.put(key, Collections.singletonList(value)));

result.entrySet().forEach(System.out::println);
Output:
SKI=[7]
IN=[30]
COR=[13]

选项4

Map<String, List<Integer>> result =
        map4.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    // key mapping
                    entry -> entry.getKey(),
                    // value mapping
                    entry -> Collections.singletonList(entry.getValue())
                    )
            );

result.forEach((key, val) -> System.out.println(key + " " + val));
Output:
SKI [7]
IN [30]
COR [13]