1

In the following method I want to replace the forEach loop with a stream.

protected Set<String> getSelectedPaths(final CheckModel<TreeItem<String>> checkModel, final LazyTreeItem root) {

      final Set<String> ceckedList = new HashSet<>();
      final List<TreeItem<String>> children = root.getChildren();
      final List<LazyTreeItem> lazyChildren = children.stream().map((item -> (LazyTreeItem) item))
            .collect(Collectors.toList());

      final List<String> selectedChildren = new ArrayList<>();
      children.forEach(child -> selectedChildren.addAll(getSelectedPaths(checkModel, (LazyTreeItem) child)));

      /**
      * do sth with checkedList
      */
     return checkedList

the lines

      final List<String> selectedChildren = new ArrayList<>();
      children.forEach(child -> selectedChildren.addAll(getSelectedPaths(checkModel, (LazyTreeItem) child)));

should be replaced with a stream. I tried with

      final List<String> selectedChildren = children.stream().map(child->getSelectedPaths(checkModel, (LazyTreeItem) child)).collect(Collectors.toList());

but the compiler error " Type mismatch: cannot convert from List<Set<String>> to List<String>" is thrown. Is there an opportunity to replace this forEach loop with a stream?

3 Answers 3

2

You try to collect a Stream<Set<String>> into a List<String>. This is obviously a type mismatch. You need to flatten the stream into a Stream<String> prior to collecting it using .flatmap(Set::stream).

Sign up to request clarification or add additional context in comments.

Comments

1

Your map operation is producing a Stream<Set<String>> (since each element of the original Stream<TreeItem<String>> is mapped to a Set<String>), which results in a List<Set<String>>.

In order to get a List<String> you need to use flatMap:

final List<String> selectedChildren = 
    children.stream()
            .flatMap(child->getSelectedPaths(checkModel, (LazyTreeItem) child).stream())
            .collect(Collectors.toList());

Comments

1

Using .flatmap after Map ,

final List<String> selectedChildren = children.stream().map(child->getSelectedPaths(checkModel, (LazyTreeItem) child)).flatMap(child.stream()).distinct().collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.