[英]Performance Improvement in finding intersection between two nested lists in Java 8
這是Java 8中的一段代碼,該代碼查找兩個不同的嵌套列表之間的交集。 當我執行此代碼時,它將對程序產生巨大的性能影響。 我試圖弄清楚代碼的哪一部分會導致性能嚴重下降。
private static List<List<Integer>> findIntersection(List<List<Integer>> processlist1,List<List<Integer>> processlist2) {
List<List<Integer>> intersect = processlist1.stream().flatMap(sl1 -> processlist2.stream().map(sl2 -> {
List<Integer> lout = new ArrayList<>();
lout.addAll(sl1);
lout.retainAll(sl2);
return lout;
})).filter(l -> l.size() > 0).distinct().collect(Collectors.toList());}
任何想法將不勝感激。
您可以通過將叉積的一側轉換為HashSet
流來避免retainAll
的二次復雜度:
List<List<Integer>> intersect = processList2.stream()
.map(HashSet::new)
.flatMap(set -> processList1.stream()
.map(list -> list.stream()
.filter(set::contains)
.collect(toList())
)
)
.filter(x -> !x.isEmpty())
.distinct()
.collect(toList());
以上假設
import static java.util.stream.Collectors.toList;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.