If you are open to using a third-party library, there are some interesting options that you could use with Eclipse Collections .
If you are using an ArrayList as described above, you can use the LazyIterate utility as follows:
int count = LazyIterate.collect(custNames, String::toLowerCase) .countWith(String::startsWith, nameStarts.toLowerCase()); Assert.assertEquals(2, count);
If you use the Eclipse collection replacement for ArrayList , you can use the rich functional protocols available directly on the 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);
The serial API in Eclipse collections compiles by default, so I called asLazy() first. A collection method would otherwise create another MutableList .
If you are comparing your code with a complete set of data, the following parallel version of the code may be more efficient:
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);
The asParallel() API in Eclipse collections is the default. The API forces you to pass in the format ExecutorService and int batchSize. This gives you full control over parallelism.
You can also use the Stream API with all MutableCollections in Eclipse collections, because they extend java.util.Collection .
Note. I am a committer for Eclipse collections.