java - 如何使用 HashMap 将多个值放入 ArrayList?

标签 java arrays hashmap

我收到了 JSON 对象,并解析了它。

数据如下。

[Parsed_showinfo_2 @ 0x9b4da80] n:88 pts:17425897 pts_time:726.079 pos:149422375 fmt:rgb24 sar:405/404 s:640x360 i:P iskey:1 type:I checksum:48E13810 plane_checksum:[48E13810]
[Parsed_showinfo_2 @ 0x9b4da80] n:89 pts:17471943 pts_time:727.998 pos:149646339 fmt:rgb24 sar:405/404 s:640x360 i:P iskey:0 type:P checksum:1AAD40E0 plane_checksum:[1AAD40E0]
[Parsed_showinfo_2 @ 0x9b4da80] n:90 pts:17503975 pts_time:729.332 pos:149806608 fmt:rgb24 sar:405/404 s:640x360 i:P iskey:1 type:I checksum:3DA5F0DB plane_checksum:[3DA5F0DB]

然后,我使用 JSONParser() 解析数据,因为我需要 pts、pts_time 值。

FileInputStream fstream = new FileInputStream("myfile");
DataInputStream in = new DataInputStream(fstream);
BufferedReader buff = new BufferedReader(new InputStreamReader(in));

//Which type put to ?
HashMap<String, ?> map = new HashMap<String, ?>();
//Should I use ArrayList too?
//ArrayList<HashMap<String, ?>> list = new ArrayList<HashMap<String, ?>>();

try {
    while (strLine = buff.readLine()) != null) {
        s = strLine.split(" ");
        pts = Long.parseLong(s[4].split(":")[1]);
        ptstime = s[5].split(":")[1];
    }
} catch (IOException ex) { }

我想在while循环中创建多个数组,并返回结果值。

像这样:

["pts": {1, 2, 3, 4, 5}, "ptstime": {10.11, 13.003, 15.12, 16.53, 18.10}]

ptsptstime 是键。

如何在 while 循环中编码

最佳答案

以下是具体操作方法:

Map<String, List<Object>> map = new HashMap<>();
...
while (strLine = buff.readLine()) != null) {
    s = strLine.split(" ");
    pts = Long.parseLong(s[4].split(":")[1]);
    List<String> listPts = map.get("pts");
    if (listPts == null) {
        listPts = new ArrayList<>();
        map.put("pts", listPts);
    }
    listPts.add(pts);
    // Here apply the same logic to the rest
}

但更好的方法可能是使用 MapList 来代替,如下所示:

List<Map<String, Object>> list = new ArrayList<>();
while (strLine = buff.readLine()) != null) {
    s = strLine.split(" ");
    Map<String, String> map = new HashMap<>();
    list.add(map);
    pts = Long.parseLong(s[4].split(":")[1]);
    map.put("pts", pts);
    // Here apply the same logic to the rest
}

关于java - 如何使用 HashMap 将多个值放入 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37183824/

相关文章:

java - 当 super() 不执行任何操作时调用它

php - 从 CURL JSON 响应 php 数组中获取特定值

c - c中2/3d数组的地址

java - 如何在 JOptionPane 中的背景图像上对齐多个文本字段?

java - 如何在 Tomcat 中为 Spring 提供一个类?

android - HashMap 作为 fragment 的参数

java - 查询HashMap内部实现

java - 遍历 hashmap : 'For' loop using Random Access OR Iterator?

java - 屏幕旋转时不保存当前Fragment和数据

java - 仅使用 for 循环组合两个不重复的 int 数组