Converting List> to Array>

后端 未结 3 1355
抹茶落季
抹茶落季 2021-01-26 08:41

I am writing a method which converts Integer data type from a List of lists, to a primitive type \"int\" of \"array of array\".

Question

<
相关标签:
3条回答
  • 2021-01-26 09:20

    This

    tempArray[i][j] = ll.get(j);
    

    should be something like

    tempArray[i][j] = ll.get(i).get(j);
    

    However, you have a few other bugs (you need to declare the arrays); you can also shorten the initialization routines. Something like,

    static int[][] convert(int[] set) {
        List<List<Integer>> ll = new ArrayList<>();
        ll.add(Arrays.asList(1,2));
        ll.add(Arrays.asList(2));
        ll.add(Arrays.asList(2,3));
    
        System.out.println(ll + " " + ll.size());
    
        int[][] tempArray = new int[ll.size()][];
        for (int i = 0; i < ll.size(); i++) {
            tempArray[i] = new int[ll.get(i).size()];
            for (int j = 0; j < tempArray[i].length; j++) {
                tempArray[i][j] = ll.get(i).get(j);
            }
        }
        return tempArray;
    }
    
    0 讨论(0)
  • 2021-01-26 09:22

    To answer your exact question, yes an Integer can be converted to an int using the intValue() method, or you can use auto-boxing to convert to an int.

    So the innermost part of your loop could be either of these:

    tempArray[i][j] = ll.get(i).get(j).intValue();
    tempArray[i][j] = ll.get(i).get(j);
    

    However, we can also take a different strategy.

    As a modification of this answer to a similar question, in Java 8 you can use Streams to map to an integer array. This structure just requires an extra layer of mapping.

    List<List<Integer>> list = new ArrayList<>();
    
    int[][] arr = list.stream()
        .map(l -> l.stream().mapToInt(Integer::intValue).toArray())
        .toArray(int[][]::new);
    

    Ideone Demo

    0 讨论(0)
  • 2021-01-26 09:23

    I think you don't need API to convert Integer to int. Just because Integer itself has its own method. Let's see following example

    Integer integerObj = new Integer(100);
    int intValue = integerObj.intValue();     // intValue = 100
    
    0 讨论(0)
提交回复
热议问题