Gabriel Gabriel - 1 month ago 7
Java Question

Fill one-dimensional Arraylist with one row of two-dimensional ArrayList

How can I fill one-dimensional

ArrayList
with one row of two-dimensional
ArrayList
? I have tried with following code:

public static List<List<Float>> matrix = new ArrayList<>();

public static void buildMatrix(List<String> URLList, List<String> headerList)
{

// DO SOME STUFF

List<Float> tempArrayList = new ArrayList<>();
tempArrayList.add(matrix.get(matrix.size()));

}


I got an error: "List cannot be applied"

Answer

Call List#addAll(Collection<? extends E> c) for each element of the List

List<Float> tempArrayList = new ArrayList<>();
for (List<Float> list : matrix) {
    tempArrayList.addAll(list);
}

If you use Java 8, it can be done thanks to the Stream API, more specifically with the method Stream#flatMap(Function<? super T,? extends Stream<? extends R>> mapper) as next:

List<Float> tempArrayList = matrix.stream()
    .flatMap(List::stream)
    .collect(Collectors.toList());