I converted the following code into java 8 code. I would like to know if i did it properly or there is some other nice way.
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 to solve 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; }
Collectors.toSet(). Or, if you need a list, add a.distinct()step after theflatMapcurrentLevel.isEmpty()?CollectionUtils.isNotEmptyand related methods are "null-safe" in that a null collection is considered empty. Not my preference, but a lot of people like this style.