[英]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.我知道这是一个非常基本的问题,但是在阅读了一些 SO 帖子和谷歌之后我无法很好地理解这个问题,所以。
I have a map object data
, a System.out.println(data)
shows me something like the following on the console:我有一个 map object
data
,一个System.out.println(data)
在控制台上显示如下内容:
{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.此外,
data
在控制台上显示LinkedHashMap@11 size=1
。
Now I wanted to have the first "engine" key value of the first array of "data", aka engine1
.现在我想拥有第一个“数据”数组的第一个“引擎”键值,也就是
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"?如何从“data”中获取“engine1”的值? Thanks for your help.
谢谢你的帮助。
edit:编辑:
The code around it is as shown below.它周围的代码如下所示。
data
is declared by Map<String, Object> data
. data
由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) (不确定您是否需要此信息,但以防万一,“student.yml”文件如下所示)
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.