[英]itinerary: making double array String into a Map of String, String (Key & Value)
I have a String[][]
. 我有一个
String[][]
。 So it basically looks like this: 所以基本上看起来像这样:
{
{ "Dublin", "NYC"},
{ "Moscow", "Los-Angeles"},
{ "London", "Paris" }
}
And I have to add them to Map
, so that Keys will be first column(Dublin, Moscow, London), and Values will be second (NYC, LA, Paris) 而且我必须将它们添加到
Map
,这样“键”将是第一列(都柏林,莫斯科,伦敦),而值将是第二列(纽约,洛杉矶,巴黎)
Can you please help, I don't know where to start 您能帮忙吗,我不知道从哪里开始
Create map 建立地图
HashMap<String, String> map = new HashMap<String, String>();
Loop over data ( String[][]). 循环数据 (String [] [])。 Each array in data is your key and value.
数据中的每个数组都是您的关键和价值。 Add them to map
将它们添加到地图
for (String[] keyValue : data) {
map.put(keyValue[0],keyValue[1]);
}
To add this array elements into a Map
, you just need to use a loop to iterate over all the key, value
pairs and add them to the a Map . 要将这个数组元素添加到
Map
,只需使用循环遍历所有key, value
对并将它们添加到Map中即可 。
This is how should be your code: 这应该是您的代码:
String[][] array = { { "Dublin", "NYC"}, { "Moscow", "Los-Angeles"}, { "London", "Paris" }};
Map<String, String> map = new HashMap<String, String>();
//loop over the array and add elements into the HashMap
for(int i=0;i<array.length;i++){
map.put(array[i][0], array[i][1]);
}
This is a live working Demo . 这是一个现场工作的演示 。
The same with java Streams: 与Java Streams相同:
String[][] array = { { "Dublin", "NYC"}, { "Moscow", "Los-Angeles"}, { "London", "Paris" }};
Map<String, String> flightsMap = Stream.of(array)
.collect(Collectors.toMap(p -> p[0], p -> p[1]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.