[英]Collection of collection's references(may be of ArrayList or any other ) and want to use those references to create collections
[英]Create collection from two other collections
在C#中,如果我有2個通用集合
SthCollection<Sth>
和
SthElseCollection<SthElse>
我可以創建第三個
SthAndSthElseCollection<Sth, SthElse>
(其中Sth和SthElse是某些對象的列表)。
如何將其“遷移”到Java? 我可以使用枚舉或其他集合類型來執行此操作嗎? 對於這些事情,我將提供一個很好的鏈接。 謝謝您的幫助
org.apache.commons.collections.CollectionUtils具有並集方法,該方法可以從2個集合中創建一個Collection。
這是鏈接: http : //commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/CollectionUtils.html
如果兩種類型之間唯一的共同超類型是Object
,則使用
List<Object> union = new ArrayList<Object>();
union.addAll(collectionOfSth);
union.addAll(collectionOfSthElse);
如果您想要的是Set
則可以對Set
進行相同的操作。
請注意,這將創建一個副本,而不是兩個集合的視圖。 如果要查看兩個集合的並集視圖,請查看Guava Sets.union()
或Iterables.concat()
。
您可以為此使用番石榴:
final Collection<T> col1 = ...;
final Collection<T> col2 = ...;
final Iterable<T> combined = Iterables.concat(col1, col12);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.