3

I need to write a method that will convert the mass into Map

1
  • 1
    You have your expected and actual reversed. Commented Jan 9, 2022 at 13:46

3 Answers 3

2

i is an array, so when you put it as the key of your Map, you get a Map<Object[],Object>.

You don't need a nested loop:

public Map<Character, Integer> arrayToMap(Object[][] args) {
    Map<Character, Integer> map = new LinkedHashMap<>();
    for (Object[] i : args) {
        map.put((Character) i[0], (Integer) i[1]);
    }
    return map;
}

Each inner array of your 2D array should become a pair of key and value in the output Map.

Sign up to request clarification or add additional context in comments.

Comments

2

Use Stream API with Callectors.toMap method:

public static Map<Character, Integer> arrayToMap(Object[][] arr) {  
  return Arrays.stream(arr)
               .collect(Collectors.toMap(o -> (Character)o[0],
                                         o -> (Integer)o[1],
                                         (oldV, newV) -> newV,
                                         LinkedHashMap::new
                                         ));
}

Comments

2

2D array in Java is an array of arrays; i.e. in your example, you have a 1D array of 1D arrays with exactly 2 elements [char, int]

public static void main(String[] args) {
    Object[][] arr = {
            { '1', 1 }, { ' ', 5 }, { '2', 2 }, { '3', 3 },
            { '4', 4 }, { '5', 5 }, { '6', 6 } };

    Map<Character, Integer> map = arrayToMap(arr);
    System.out.println(map);
}

public static Map<Character, Integer> arrayToMap(Object[][] arr) {
    Map<Character, Integer> map = new HashMap<>();

    for (int i = 0; i < arr.length; i++)
        map.put((char)arr[i][0], (int)arr[i][1]);

    return map;
}

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.