如何将 HashMap 值添加到 ArrayList

问题描述 投票:0回答:4

我有一个 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 个不同的 ArrayList 及其相应的值?如何做到这一点?

java arraylist hashmap
4个回答
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));
}

0
投票

我不太确定您的哈希图包含什么,因为您的代码非常简短,但它几乎看起来像是为您提供了哈希图的 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
    }

但是,如果您正确地迭代哈希图,那么下面是手动将该字符串解析为三个不同数组列表的解决方案,这可能是最安全的方法。

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]);
        }
    }

}

0
投票

这是一个充满 HashMap 的 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");

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]
© www.soinside.com 2019 - 2024. All rights reserved.