0

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

3 Answers 3

1

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.