How to convert a collection <Collection <Double>> to a list <List <Double>?

I have the following field

Collection<Collection<Double>> items

and I want to convert it to

List<List<Double>> itemsList

I know that I can convert Collectionto Liston list.addAll(collection), but how can I convert Collectionfrom Collections?

+4
source share
1 answer

You can use streams:

List<List<Double>> itemsList =
    items.stream() // create a Stream<Collection<Double>>
         .map(c->new ArrayList<Double>(c)) // map each Collection<Double> to List<Double>
         .collect(Collectors.toList()); // collect to a List<List<Double>>

or using a method reference instead of a lambda expression:

List<List<Double>> itemsList =
    items.stream() // create a Stream<Collection<Double>>
         .map(ArrayList::new) // map each Collection<Double> to List<Double>
         .collect(Collectors.toList()); // collect to a List<List<Double>>

To solve Java 7, you need a loop:

List<List<Double>> itemsList = new ArrayList<List<Double>>();
for (Collection<Double> col : items)
    itemsList.add(new ArrayList<Double>(col));
+10
source

Source: https://habr.com/ru/post/1660059/


All Articles