我爲多個集合的統一以下功能(包括重複的元素)多個集合的路口:Java中使用流+ lambda表達式
public static <T> List<T> unify(Collection<T>... collections) {
return Arrays.stream(collections)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
這將是很好有一個函數與一個類似的簽名交集(使用類型相等)。例如:
public static <T> List<T> intersect(Collection<T>... collections) {
//Here is where the magic happens
}
我發現交叉功能的實現,但它不使用流:
public static <T> Set<T> intersect(Collection<? extends Collection<T>> collections) {
Set<T> common = new LinkedHashSet<T>();
if (!collections.isEmpty()) {
Iterator<? extends Collection<T>> iterator = collections.iterator();
common.addAll(iterator.next());
while (iterator.hasNext()) {
common.retainAll(iterator.next());
}
}
return common;
}
有什麼辦法來實現類似功能的統一利用流的東西嗎?我在java8/stream api中沒有那麼經驗,因爲有些建議會非常有用。
爲什麼你認爲你需要流? –
僅僅是好奇心!我同意提及,我真的是新的Java 8 /流API,所以我目前正試圖學習更多的使用api :) –
正確。就我個人而言,我覺得學習這些API的最好方法就是嘗試自己解決這樣的問題。試試看,如果您遇到困難,請回來一個**特定**問題,概述您的問題。 –