Java如何将数组转换为Map?
本示例使用ApacheCommonsLang的ArrayUtils.toMap()方法将二维数组转换为Map对象。
要将二维数组转换为Map对象,二维数组的每个元素必须是至少包含两个元素的数组,其中第一个元素将是键,第二个元素将是值。
package org.nhooo.example.commons.lang;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
public class ArrayToMapExample {
public static void main(String[] args) {
//国家资本的二维数组。
String[][] countries = {{"United States", "Washington, D.C."},
{"United Kingdom", "London"},
{"Netherlands", "Amsterdam"},
{"Japan", "Tokyo"},
{"France", "Paris"}};
//将数组转换为Map。
Map capitals = ArrayUtils.toMap(countries);
for (Object key : capitals.keySet()) {
System.out.printf("%s is the capital of %s.%n", capitals.get(key), key);
}
}
}我们的代码片段的结果:
London is the capital of United Kingdom. Amsterdam is the capital of Netherlands. Paris is the capital of France. Washington, D.C. is the capital of United States. Tokyo is the capital of Japan.
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短