Vitalii Smahlenko
Vitalii Smahlenko

Reputation: 99

How to write method array to Map

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

Upvotes: 3

Views: 350

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18255

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;
}

Upvotes: 2

Sergey Afinogenov
Sergey Afinogenov

Reputation: 2202

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

Upvotes: 2

Eran
Eran

Reputation: 393946

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.

Upvotes: 2

Related Questions