Home > Blockchain >  How can I correctly input a List<List<Integer>> in my main method?
How can I correctly input a List<List<Integer>> in my main method?

Time:11-15

I have a function that takes data from a 2D array and stores it in a Hashmap. I just want to know that how can I input a 2D int array correctly in my main function. Here is what I have so far:

public class Sorted {

    public static void countSort(List<List<Integer>> inputData) {
        Map<Integer, List<Integer>> dataAsMap = new HashMap<>();
        for(List<Integer> row : inputData) {
            Integer id = row.get(0); 
            Integer item = row.get(1);
            List<Integer> rowInMap = dataAsMap.get(item);
            if (rowInMap == null) {
                rowInMap = new ArrayList<>();
                dataAsMap.put(item, rowInMap);
            }
       
            rowInMap.add(id);
        }
    }
 
        
    public static void main(String[] args) {
        int[][] newArray = {{ 1, 2, 3}, {101, 102, 103}};
        Arrays.countSort(newArray);
    }    
} 

Unless you haven't noticed already, this code wouldn't even compile. I believe that [[1, 2, 3], [100, 101, 102]] is indeed a 2D integer array but my issue is that I have no idea how to implement it in the countsort() function. Can anyone please help?

CodePudding user response:

If you need to create a multi dimensional array list then try with below code,

public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1); list1.add(2); list1.add(3);
        
        List<Integer> list2 = new ArrayList<>();
        list2.add(101); list2.add(102); list2.add(103);
        
        List<List<Integer>>  main = new ArrayList<>();
        main.add(list1);
        main.add(list2);
        
        Sorted.countSort(main);
}

In your main method final line,

Arrays.countSort(newArray);

I don't think this is correct. It should your class name.

CodePudding user response:

        List<List<Integer>> list = new ArrayList<List<Integer>>();

        int addable = 1;
        for(int i = 1; i <= 3; i  ) {
            List<Integer> innerList = new ArrayList<Integer>();
            for(int j = addable; j <= addable   3; j  ) {
                innerList.add(j);
            }
            addable  = 100;
            list.add(innerList);
        }

        System.out.println(list);

which will output

[[1, 2, 3, 4], [101, 102, 103, 104], [201, 202, 203, 204]]

  • Related