简体   繁体   中英

Get value from ArrayList object in Java?

I know this is a quite basic question, but after reading some SO posts and google I couldn't understand the issue well, so.

I have a map object data , a System.out.println(data) shows me something like the following on the console:

{data=[{engine=engine1, keyword=keyword1, url=url1}, {engine=engine2, keyword=keyword2, url=url2}]}

Also, a data shows me LinkedHashMap@11 size=1 on the console.

Now I wanted to have the first "engine" key value of the first array of "data", aka engine1 .

Before that I tried to obtain the first of the array, so I tried the following, but I get errors.

data.get("data")[1]
Cannot evaluate because of compilation error(s): The type of the expression must be an array type but it resolved to Object.

data.get("data").get(1)
Cannot evaluate because of compilation error(s): The method get(int) is undefined for the type Object.

How can I obtain the "engine1" value from "data"? Thanks for your help.

edit:

The code around it is as shown below. data is declared by Map<String, Object> data .

import org.yaml.snakeyaml.Yaml;

~~ 

InputStream inputStream = new FileInputStream(new File("student.yml"));

Yaml yaml = new Yaml();
Map<String, Object> data = yaml.load(inputStream);
System.out.println(data);

(not sure you need this info but just in case, "student.yml" file is as shown below)

data: 
  - engine: engine1
    keyword: keyword1
    url: url1
  - engine: engine2
    keyword: keyword2
    url: url2

Updating answer post question edit; Please find below, the solution you want;

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

public class YamlParser {

    public static void main(String[] args) throws FileNotFoundException {

        InputStream inputStream = new FileInputStream(new File("src/main/resources/student.yml"));

        Yaml yaml = new Yaml();
        Map<String, Object> data = yaml.load(inputStream);
        System.out.println(data); // Prints full map
        List<Map<String,String>> eng = (List<Map<String,String>>) data.get("data"); //Casting object to List
        System.out.println(eng.get(0).get("engine")); // Prints the value : engine1
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM