从ArrayList中的HashMap获取键和值

史蒂夫·库尔特(Steve Coulter):

我有一个文件,可以获取所有数据并将其分离为HashMap。该文件如下所示。

之前:key,之后是value

key1: 1
key2: 2
key3: 3

这是将文件数据放入映射ArrayList的代码:

protected List<Map<String, String>> yaml_parse(BufferedReader filename) throws IOException{

    String result;
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    while ((result = filename.readLine()) != null) {
        Map<String, String> map = new HashMap<String, String>();
        String key = result.substring(0, result.indexOf(":"));
        String value = result.substring(result.lastIndexOf(":") + 2);
        map.put(key, value);
        list.add(map);
    }

    return list;
}

在另一个我调用函数和println的类中,这是输出

[{key1=1}, {key2=2}, {key3=3}]

所以我的主要问题是,我如何获得key1并返回其价值?

拉加夫:

我不明白您为什么要创建List地图。A Map将让您放置几个键值对。这是一种可行的方法:

protected Map<String, String> yaml_parse(BufferedReader filename) throws IOException{
    String result;
    Map<String, String> map = new HashMap<String, String>();
    while ((result = filename.readLine()) != null) {
        //keyValue[0] = key, keyValue[1] = value
        String[] keyValue = result.split(": "); 
        map.put(keyValue[0], keyValue[1]);
    }

    return map;
}

您将像这样使用它:

Map<String, String> map = yaml_parse("myFile.yaml");
String key1Value = map.get("key1"); //Stores key1's value into key1Value

我认为您可能使用了错误的数据结构。从你的问题,好像你想要一个Map而已,不是ListMaps

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章