Home > database >  How to convert two-dimensional array to linkedhashmap in java
How to convert two-dimensional array to linkedhashmap in java

Time:01-10

I am learning Java Programming.

I have a task, need to convert a two-dimensional array to a Map<Character, Integer> for testing.

Object[][] args = new Object[][]{
                {'1', 1},
                {' ', 5},
                {'2', 2},
                {'3', 3},
                {'4', 4},
                {'5', 5},
                {'6', 6}};

Map<Character, Integer> expectedResult = arrayToMap(args);

I wrote a method:

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

But I can’t understand why it doesn’t convert Character. Input:

Expected :{[Ljava.lang.Object;@6b1274d2=1, [Ljava.lang.Object;@7bc1a03d=5, [Ljava.lang.Object;@70b0b186=2, [Ljava.lang.Object;@ba8d91c=3, [Ljava.lang.Object;@7364985f=4, [Ljava.lang.Object;@5d20e46=5, [Ljava.lang.Object;@709ba3fb=6}
Actual   :{1=1,  =5, 2=2, 3=3, 4=4, 5=5, 6=6}

Please advise, what I'm doing wrong

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

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;
}
  •  Tags:  
  • Related