0

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.

1
  • Just to be sure, getAllPredicates is a static method, right? Commented Apr 21, 2014 at 9:55

1 Answer 1

3

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.

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

6 Comments

Somehow the compiler doesn't like InMemoryGraph::getAllPredicates, it keeps asking to define a local variable or a field with the name InMemoryGraph, which is the name of the class. getAllPredicates is a public static method in that class. Any ideas?
Do you need to import the class maybe?
You could also try the equivalent lambda: .map(s -> InMemoryGraph.getAllPredicates(s)) and see what message you get. Can you confirm that the method signature is public static Set<Node> getAllPredicates(String s)?
this line is in another static method within the same class. I used s -> InMemoryGraph.getAllPredicates(s) as well it says create a local variable called s!!
@Arsham are you sure you are compiling for Java 8 (and not Java 7)? Have you managed to create a simple program with a lambda?
|

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.