Reputation:
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 Collection
s?
Upvotes: 4
Views: 198
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