簡體   English   中英

從其他兩個集合創建集合

[英]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);

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#concat(java.lang.Iterable ...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM