gpt4 book ai didi

java - 从 Map 获取键值对

转载 作者:行者123 更新时间:2023-11-29 03:14:27 24 4
gpt4 key购买 nike

我有这段代码来检索 map 的键值对:

countries = BeneficiaryJSONParser.parseCountriesFeed(result);
for(Map.Entry<String, Object> entry: countries.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}

输出:

data : [{234=United Arab Emirates, 103=India, 210=Sri Lanka, 235=United Kingdom, 216=Switzerland, 200=Singapore, 76=France}]
status : 200
code : 1

我想获取包含键和值的数组形式的数据。因为,我想将那些键值对放入,

final MyData items[] = new MyData[3];
items[0] = new MyData( "234","United Arab Emirates" );
items[1] = new MyData( "103","India" );
items[2] = new MyData( "210","Sri Lanka" );
.
.
.

最佳答案

您只需将每个条目转换为 MyData:

List<MyData> data = new ArrayList<> ();
for (Map.Entry<String, Object> e: countries.entrySet()) {
data.add(new MyData(e.getKey(), String.valueOf(e.getValue());
}

final MyData[] items = data.toArray(new MyData[0]);

或者使用流:

final MyData[] items = countries.entrySet().stream()
.map(e -> new MyData(e.getKey(), String.valueOf(e.getValue()))
.toArray(MyData[]::new);

关于java - 从 Map 获取键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27490347/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com