如果您愿意使用第三方库,您可以使用Eclipse Collections 使用一些有趣的选项。
如果您使用上面的ArrayList,您可以使用LazyIterate 实用程序,如下所示:
int count = LazyIterate.collect(custNames, String::toLowerCase)
.countWith(String::startsWith, nameStarts.toLowerCase());
Assert.assertEquals(2, count);
如果您使用 Eclipse Collections 替代 ArrayList,您可以使用直接在 MutableList 上提供的丰富功能协议:
MutableList<String> custNames =
Lists.mutable.with("John", "Tom", "Bart", "Tim", "Broad");
String nameStarts= "T";
int count = custNames.asLazy()
.collect(String::toLowerCase)
.countWith(String::startsWith, nameStarts.toLowerCase());
System.out.println(count);
Assert.assertEquals(2, count);
Eclipse Collections 中的串行 API 默认是 Eager-by-default,这就是我首先调用 asLazy() 的原因。否则 collect 方法会创建另一个 MutableList。
如果您使用完整的数据集对代码进行基准测试,则以下代码的并行版本可能会更高效:
MutableList<String> custNames =
Lists.mutable.with("John", "Tom", "Bart", "Tim", "Broad");
String nameStarts= "T";
int processors = Runtime.getRuntime().availableProcessors();
int batchSize = Math.max(1, custNames.size() / processors);
ExecutorService executor = Executors.newFixedThreadPool(processors);
int count = custNames.asParallel(executor, batchSize)
.collect(String::toLowerCase)
.countWith(String::startsWith, nameStarts.toLowerCase());
executor.shutdown();
Assert.assertEquals(2, count);
Eclipse Collections 中的asParallel() API 默认是惰性的。 API 强制您传入 ExecutorService 和 int batchSize。这使您可以完全控制并行度。
您还可以将 Stream API 与 Eclipse Collections 中的所有 MutableCollections 一起使用,因为它们扩展了 java.util.Collection。
注意:我是 Eclipse Collections 的提交者。