0

So i'm creating a method that looks like this:

public static ArrayList<int[]> permuteArray(int[] array)

I have a helper method that looks like this:

  public static List<List<Integer>> permuteArray(List<List<Integer>> list, List<Integer> result, int [] arr) {
    if(result.size() == arr.length){
        list.add(new ArrayList<>(result));
    }
    else{
        for(int i = 0; i < arr.length; i++){
            if(result.contains(arr[i]))
            {
                continue;
            }
            result.add(arr[i]);
            permuteArray(list, result, arr);
            result.remove(result.size() - 1);
        }

    }
    return list;
}

I have this line : List<List<Integer>> permute = permuteArray(list, new ArrayList<>(), array); But i want to convert the List<List<Integer>> to ArrayList<int[]>. Is this possible for the helper method to return ArrayList<int[]> or if the original method can?

5
  • Are you asking if the helper method can directly return an ArrayList<int[]> instead of List<List<Integer>>? It probably can. It would be easier to answer if you included the code of that method. Commented Jul 12, 2020 at 5:57
  • I'll add it right now Commented Jul 12, 2020 at 5:59
  • @Eran i just added the method Commented Jul 12, 2020 at 6:01
  • Why do you want to return an ArrayList specifically? Commented Jul 12, 2020 at 6:02
  • practicing with array-list and the prompt wants me to return an ` ArrayList<int[]>` Commented Jul 12, 2020 at 6:04

3 Answers 3

4

Try this:

List<List<Integer>> lst = new ArrayList<>();
lst.add(List.of(1, 2, 3));
lst.add(List.of(4, 5, 6));
lst.add(List.of(7,8,9));

ArrayList<int[]> newList = lst.stream()
        .map(x -> x.stream().mapToInt(k -> k).toArray())
        .collect(Collectors.toCollection(ArrayList::new));
Sign up to request clarification or add additional context in comments.

Comments

2

While modifying the original method might be the better way to go, this is the answer to the title, which is 'Converting List<List<Integer>> to ArrayList<int[]>'

List<List<Integer>> original = ...;
ArrayList<int[]> arraylist = original.stream()
    .map(sub -> sub.stream().mapToInt(i -> i).toArray())
    .collect(Collectors.toCollection(ArrayList::new));

Comments

0

You can also try using the below to convert List<List> to ArrayList<int[]>,

list.stream().map(x -> x.stream().mapToInt(Integer::intValue).toArray())
                .collect(Collectors.toCollection(ArrayList::new));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.