如何使用并行流来执行此功能



这是我对该函数的解决方案。它有效,但我需要使用并行流来更快地进行计算。

public static List<String> findWinners(String pattern, int minLength, boolean even, Stream<String> stream){
return stream.filter(x -> x.matches(pattern) && x.length() >= minLength).filter(x -> x.length() % 2 == (even ? 0 : 1))
.sorted(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
}).collect(Collectors.toList());
}

您应该编译pattern。试试这个。

public static List<String> findWinners(String pattern, int minLength, boolean even, Stream<String> stream) {
Pattern compiled = Pattern.compile(pattern);
return stream.parallel()
.filter(x -> compiled.matcher(x).matches() && x.length() >= minLength)
.filter(x -> x.length() % 2 == (even ? 0 : 1))
.sorted(Comparator.comparing(String::length))
.collect(Collectors.toList());
}

您可以使用ForkJoinPool对并行流进行自定义,方法是使用8个线程来取消并行流,但对于巨大的数据,有时需要花费更多的时间。

在这里你可以为并行流做定制:

public static List<String> findWinners(String pattern, int minLength, boolean even, Stream<String> stream) throws InterruptedException, ExecutionException {
int numberOfThreads = 20;
ForkJoinPool forkJoinPool = new ForkJoinPool(numberOfThreads);
List<String> winners = forkJoinPool.submit(() -> {
return stream.parallel()
.filter(x -> x.matches(pattern) && x.length() >= minLength)
.filter(x -> x.length() % 2 == (even ? 0 : 1))
.sorted(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
}).collect(Collectors.toList());
}).get();

return winners;
}

最新更新