简体   繁体   中英

itinerary: making double array String into a Map of String, String (Key & Value)

I have a 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)

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[][]). 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 .

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:

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]));

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