【问题标题】:How to add HashMap values into an ArrayList如何将 HashMap 值添加到 ArrayList
【发布时间】:2013-02-08 13:16:13
【问题描述】:

我有一个 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 及其对应的值吗?该怎么做?

【问题讨论】:

  • 您的数据是否始终为 JSON?
  • 我不能使用 JSON 吗?我们不能用正常的方式来做吗?
  • 这个问题和Android有什么关系?

标签: java arraylist hashmap


【解决方案1】:

如果您的数据始终是 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));
}

【讨论】:

  • 我不能使用 JSON 吗?我们不能用正常的方式来做吗?
  • 您必须手动解析字符串。拆分, ,然后拆分每个元组=。
【解决方案2】:

我不太确定你的 hashmap 包含什么,因为你的代码很简短,但看起来它几乎给了你 hashmap 的 toString()。遍历 hashmap 的最佳方法是:

    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,那么下面是手动将该字符串解析为三个不同的数组列表的解决方案,这可能是最安全的方法。

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

}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

      三个这样的列表:

      [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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-17
        • 1970-01-01
        • 2017-06-12
        • 1970-01-01
        相关资源
        最近更新 更多