简体   繁体   中英

Convert ArrayList<ArrayList<Integer>> to List<List<Integer>>

I have my Integer data in Array Lists of Arrays Lists and I want to convert that data to Lists of List format. How can I do it?

public List<List<Integer>> subsetsWithDup(int[] nums) {

    ArrayList<ArrayList<Integer>> ansList = new ArrayList<ArrayList<Integer>>();

    String arrStr = nums.toString();
    ArrayList<Integer> tempList = null;

    for(int i = 0 ; i < arrStr.length()-1 ; i++){
        for(int j = i+1 ; j<arrStr.length() ; j++){

            tempList = new ArrayList<Integer>();

            tempList.add(Integer.parseInt(arrStr.substring(i,j)));

        }

        if(!ansList.contains(tempList)){
            ansList.add(tempList);
        }

    }
    return ansList;
}

It would be best to share the code where you have this issue. However, you should declare the variables as List<List<Integer>> , and then instantiate using an ArrayList .

For example:

public static void main (String[] args) throws java.lang.Exception
{

   List<List<Integer>> myValues = getValues();
   System.out.println(myValues);

}

public static List<List<Integer>> getValues() {
   List<List<Integer>> lst = new ArrayList<>();
   List<Integer> vals = new ArrayList<>();

   vals.add(1);
   vals.add(2);
   lst.add(vals);

   vals = new ArrayList<>();
   vals.add(5);
   vals.add(6);
   lst.add(vals);       

   return lst;
}

In general, program to an interface (such as List ) .

Based upon the edit to the OP's question, one can see that, as originally suggested, one can change:

ArrayList<ArrayList<Integer>> ansList = new ArrayList<ArrayList<Integer>>();

to

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

And

 ArrayList<Integer> tempList = null;

to

List<Integer> tempList = null;

And the code will then conform to the method's return signature of List<List<Integer>> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM