Please explain how it looks in the code. Those. There are arrays of type int and how to drive them into the method:

public List<Integer> convert (List<int[]> list) { } 

Description: With this method, you must go through all the elements of all the arrays in the list and add them to one common Integer sheet. Arrays in the list can be of different sizes. For example:

 list.add(new int[]{1, 2}); list.add(new int[]{3, 4, 5, 6}); List<Integer> result = convertList.convert(list); 

List<Integer> result will contain the elements: (1, 2, 3, 4, 5, 6) .

I don’t understand how to convert them to type List<int[]> list .

  • Tell us what the method should do. Give an example of the input and output list. - default locale
  • In this method, you must go through all the elements of all the arrays in the list and add them to one common Integer sheet. Arrays in the list can be of different sizes. For example: list.add (new int [] {1, 2}) list.add (new int [] {3, 4, 5, 6}) List <Integer> result = convertList.convert (list) List <Integer> result will contain the elements: (1, 2, 3, 4, 5, 6) - Terasan
  • Generics in java cannot be of a primitive type. You can pass List<Integer[]> , and in the method create a result list and add Arrays.asList(<your_array>) . - Stas Dorozhko
  • one
    @StasDorozhko cannot be used as a generic primitive (List <int>), and an array of primitives (List <int []>) can be - Nikolay
  • It’s not quite clear what the question is: do you need to write a method or call it? It is better to concentrate on one thing. - default locale

1 answer 1

An example using the Stream API:

 public List<Integer> convert(List<int[]> list) { return list.stream().flatMapToInt(Arrays::stream).boxed().collect(Collectors.toList()); } 

Example "the old fashioned way":

 public static List<Integer> convert(List<int[]> list) { List<Integer> result = new ArrayList<>(); for (int[] ints: list) { for (int i: ints) { result.add(i); } } return result; } 

Call:

 List<Integer> result = convert(asList(new int[]{1, 2}, new int[]{3, 4, 5, 6})); System.out.println(result); 

[1, 2, 3, 4, 5, 6]