简体   繁体   English

Java Collection:如何转换Collection <List<String> &gt;到ArrayList <List<String> &gt;或列表 <List<String> &gt;?

[英]Java Collection: what to convert Collection<List<String>> to ArrayList<List<String>> or List<List<String>>?

I am using Multimap<String, List<String>> in one of my API's. 我在我的API之一中使用Multimap<String, List<String>> Now to get all the values means list of list I used the .values() method of the multimap. 现在要获取所有值,意味着列表列表,我使用了multimap的.values()方法。 But this method is returning me Collection<List<String>> . 但是此方法返回Collection<List<String>> Now to play on the index on this collection I want to convert it into List<List<String>> or ArrayList<List<String>> . 现在要播放此集合的索引,我想将其转换为List<List<String>>ArrayList<List<String>>

How to cast or convert without building new arrayList and explicit add list values from collections to that arraylist. 如何在不构建新的arrayList的情况下进行强制转换或转换,以及将集合中的显式添加列表值添加到该arraylist。

You can use the appropriate constructor: 您可以使用适当的构造函数:

List<List<String>> yourList = new ArrayList<>(yourCollection);

The order of the elements in the list is the order of the iterator of the collection. 列表中元素的顺序是集合的迭代器的顺序。

If you don't want to build a new collection (and don't forget, that may not be costly since you'll create the new collection but not clone the actual members), why not just do 如果您不想建立一个新集合(并且不要忘记,这可能不会很昂贵,因为您将创建新集合但不克隆实际成员),为什么不做呢?

int i = 0;
for (List<String> list : collection) {
   // whatever
   i++;
}

Not hugely nice, I appreciate. 不太好,我很感激。

或使用Google Collection API

List<List<String>> = Lists.newArrayList(myMap.values());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 转换收藏流 <String[]> 列出 <String> [] - Convert Stream of Collection<String[]> to List<String>[] 如何转换ArrayList <ArrayList<String> &gt;列表 <List<String> &gt;在Java? - How to convert an ArrayList<ArrayList<String>> to List<List<String>> in Java? 如何将Scala集合Seq [(Int,Seq [String])]转换为Java集合List [(int,List [String])]? - How to convert Scala collection Seq[(Int, Seq[String])] to Java collection List[(int, List[String])]? 是列表 <List<String> &gt; Collection的一个实例 <Collection<T> &gt;? - Is List<List<String>> an instance of Collection<Collection<T>>? 转换scala.collection.Seq的Java对象 <String> 到python列表 - Convert Java object of scala.collection.Seq<String> to python list Java:清单 <List<String> &gt; list = new ArrayList &lt;&gt;(); - Java: List<List<String>> list = new ArrayList<>(); Java 流到可空字符串列表的集合 - Java stream to collection for nullable string list 使用 java 中的 Stream 将列表字符串转换为 ArrayList 浮点数 - Convert a List String to an ArrayList Float with Stream in java 8 转换收藏<Object>列出<String> - Converting Collection<Object> to List<String> 使用Java8将Map <String,NavigableMap <Long,Collection <String >>>转换为List <String> - Convert Map<String, NavigableMap<Long, Collection<String>>> to List<String> using Java8
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM