2016-09-20 28 views
1

如何獲得連擊「值列表」在地圖中創建一個列表,然後傳遞到另一個方法:如何將「列表類型的Hashmap值」轉換爲Set?

Map<Long,List<Long>> activities = new HashMap(); 
for(Something s: something){ 
    activities .put(prosessLongID, listOfSubProcesses); 
} //There are 5 something and for each there are 2 List of Subprocesses which makes 10 Subprocesses 

我想從上面的地圖拼接子進程的列表來創建一個集:

ImmutableSet.copyOf(listOfSubProcesses_ForAllSomething) //com.google.common.collect 

Map中有沒有任何方法返回單個列表中的所有SubProcesses列表,我可以通過上面的方法?

注意:我在Java 8上得到了@Eran的迴應,並且非常感謝。但請考慮Java 6和其他循環的解決方案。我有APache Commons和Guava的設施。 :)

+1

有一個方法'集合值()',所有你需要做的是檢查的文件.. 。 – Lucas

回答

1

您可以使用Java 8流API來收集所有的List s轉換爲單Stream,然後到一個單一的List

List<Long> listOfSubProcesses_ForAllSomething = 
    activities.values().stream().flatMap(List::stream).collect(Collectors.toList()); 
+0

Thanks.But我現在沒有使用Java-8。 Upvote for Java for Java 8.那麼Java 6 – fatherazrael

+2

@fatherazrael然後使用循環和addAll將每個列表的元素添加到單個列表中。 – Eran

+0

我明白了。 Guava或Apache Common中沒有任何快捷方式或庫方法? – fatherazrael

4

如果你不能使用Java 8個流,利用番石榴的FluentIterable (和Map#values()如@Lukas在評論中提及):

ImmutableSet<Long> subprocessIds = FluentIterable.from(activities.values()) 
     .transformAndConcat(Functions.identity()) 
     .toSet(); 

FluentIterable#transformAndConcat相當於Stream#flatMap,恆等函數確實有效諾斯ING,所以它是直接翻譯自@葉蘭的Java 8回答番石榴和Java 7

或者您可以使用Iterables#concat達到不流利的電話相同的結果:

ImmutableSet<Long> subprocessIds = ImmutableSet.copyOf(
     Iterables.concat(activities.values())); 

什麼你真正想要做的是使用正確的數據結構,在這裏:(?或者甚至SetMultimapListMultimap

ListMultimap<Long, Long> activities = ArrayListMultimap.create(); 
activities.putAll(1L, ImmutableList.of(2L, 32L, 128L)); 
activities.put(3L, 4L); 
activities.put(3L, 8L); 

因爲Multimap#values()給你你需要什麼(如Collection視圖,因此如果neccessary複製到Set):

ImmutableSet<Long> subprocessIds = ImmutableSet.copyOf(activities.values()); 
+0

謝謝。我會嘗試這些並將其標記爲答案。 :) – fatherazrael

相關問題