A better way to use Java 8
•
Java
I convert the following code into Java 8 code I wonder if I'm doing it right or if there are other good ways
Java 7
for (final Category category : categories) { final List<Category> subCategories = getCategories(category); if (subCategories != null) { currentLevel.addAll(subCategories); } }
Java8
categories.stream().map(category -> getCategories(category)).filter(list->list!=null).flatMap(cat -> cat.parallelStream()).collect(Collectors.toList())
Any Java 8 way parses the following code into a compact form
while (CollectionUtils.isNotEmpty(currentLevel)) { for (final Iterator<Category> iterator = currentLevel.iterator(); iterator.hasNext();) { final Category category = iterator.next(); if (result == null) { result = new HashSet<Category>(); } if (!result.add(category)) { // avoid cycles by removing all which are already found iterator.remove(); } } if (currentLevel.isEmpty()) { break; } final Collection<Category> nextLevel = getAllSubcategories(currentLevel); currentLevel = nextLevel; }
Solution
Your solution is OK, but it's useless to map parallel to parallel streams If you look at the implementation of flatmap in openjdk / Oracle JDK, you can see that the flow created through the lambda passed to flatmap will immediately change to sequential mode So you won't have any parallelism. It's best to replace parallelstream () with stream () to avoid confusion If you really want to parallelize work, it is usually best to parallelize only the outermost streams
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码