1

I have a file that i get all the data and separate it into a HashMap. The file looks something like this below.

Before the : is the key and after is the value

key1: 1
key2: 2
key3: 3

this is the code that puts the file data into the map 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;
}

in another class where i call the function and println, this is the output

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

So my Main question is, how do i get key1 and have it return its value?

3
  • the what about list has two Map objects and each map has key1? Commented Feb 11, 2019 at 0:20
  • the list has 3 map objects in it, which are: [{key1=1}, {key2=2}, {key3=3}] Commented Feb 11, 2019 at 0:23
  • Why on earth would you build a list of single-entry maps? That makes no sense. If you're using the map as a holder of a key/value pair, then stop being lazy and create a class, then have a list of that class. Commented Feb 11, 2019 at 0:27

4 Answers 4

2

I don't understand why you are creating a List of maps. A Map will let you put several key value pairs. Here is a way that would work:

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

And you would use it like this:

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

I think you might be using the wrong data structure. From your question, it seems like you want a Map only, not a List of Maps.

Sign up to request clarification or add additional context in comments.

Comments

2

You should look at changing your List<Map> to a Map. You can do this using:

Map<String, String> map = list.stream()
        .flatMap(m -> m.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

If you want to work with your current data structure, you can get the required value like this:

private Optional<String> getValue(List<Map<String, String>> list, String key) {
    return list.stream()
            .filter(m -> m.containsKey(key))
            .map(m -> m.get(key))
            .findFirst();
}

and use it as follows:-

Optional<String> value = getValue(list, "key2");
System.out.println(value.orElse(null));

Comments

2

So if you are interested in using java-8, if list of map contains any of entry with key as key1 will return the first entry value else it will return the default value

list.stream().flatMap(map->map.entrySet().stream().filter(entry->entry.getKey().equals("key1"))).findFirst()
  .orElse(new AbstractMap.SimpleEntry("key1", "default value")).getValue();

Just by using normal for loop

for(Map<String, String> map : list) {
        if(map.containsKey("key1")) {
            result = map.get("key1");
            break;
        }
    }

Comments

1

Are you sure this is the data structure you want?

A map can contain more than 1 key/value pair. Why not have a single hashmap here, containing all 3 key/value pairs, at which point, you can just do:

map.get("key1")

and it'll still be fast even if you have millions of these.

If you are making single-size maps and putting them into an arraylist because you want to preserve order, use LinkedHashMap. If you need to be capable of dealing with repeated keys, use guava's Multimap, or make a Map<String, List<String>>.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.