Вопрос

I am messing around with Java 8 lambda and I was trying to do the following but apparently I am doing something very wrong. I have an array of string String [] q and I was trying to call a static method that returns a set of Node objects for each element in the array. Here is what I wrote:

Set<Set<Node>> sets = Arrays.asList(q).stream().forEach(InMemoryGraph::getAllPredicates);

getAllPredicates is a method that accepts a String as an argument and returns a Set<Node> Do I need to use java.util.function? Any suggestion is appreciated.

Это было полезно?

Решение

So:

  • you have an array which you want to stream: Arrays.stream(q)
  • then you want to map each string to a set of node: .map(InMemoryGraph::getAllPredicates)
  • and collect those sets in a set: .collect(toSet());

in one go:

Set<Set<Node>> sets = Arrays.stream(q) //a Stream<String>
                       .map(InMemoryGraph::getAllPredicates) // a Stream<Set<Node>>
                       .collect(toSet()); // a Set<Set<Node>>

Note: you need a static import of Collectors.toSet.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top