user7126137
user7126137

Reputation:

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 a

List<List<Double>> itemsList

I know that I can convert a Collection to a List by list.addAll(collection), but how can I convert a Collection of Collections?

Upvotes: 4

Views: 198

Answers (1)

Eran
Eran

Reputation: 393771

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 with a method reference instead of the 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>>

A Java 7 solution would require a loop :

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

Upvotes: 10

Related Questions