Erik
Erik

Reputation: 479

How do I convert a for loop to a stream

I've learned a little bit about streams and know they can be used instead of loops. For this toy example, I'm using a graph database to store a set of Strings. The dB stores them as vertices. I'd like to retrieve those vertices and convert them to Strings, using a stream, instead. Each vertex has a set of properties; I give it a key and it returns a value. If a vertex has the property I'm looking for, I add it to the list. If it doesn't I store the vertex iD.

I have a for loop but I'm not sure how to use a stream instead. Here is the code:

public List<String> getItems() throws Exception {
    Iterable<Vertex> myNodes = graph.getVertices();

    List<String> myItems = new ArrayList<>();

    // maybe there is a way to use stream API instead?
    for(Vertex v : myNodes)
    {
      String value = v.getId().toString();
      if(v.getPropertyKeys().contains(key))
      {
         value = v.getProperty(key);
      }

      myItems.add(value);
    }

    return myItems;
  }

Upvotes: 2

Views: 2298

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 30995

You need to transform the Iterables into a Stream, to do this you can leveragae StreamSupport.

This post have a nice explanation Why does Iterable<T> not provide stream() and parallelStream() methods?

You can use something like this:

StreamSupport.stream(graph.getVertices().spliterator(),false)
    .map(g -> g.getProperty(key))
    .collect(Collectors.toList());

Upvotes: 0

Flown
Flown

Reputation: 11740

As Sagar Rohankar pointed out in his answer, you need to get the Spliterator from your Iterable. Then your task is a simple one-liner:

return StreamSupport.stream(graph.getVertices().spliterator(), false)
    .map(v -> v.getPropertyKeys().contains(key) ? v.getProperty(key) : v.getId().toString())
    .collect(Collectors.toList());

Upvotes: 1

sagarr
sagarr

Reputation: 1212

Please see this SO thread. Convert Iterable to Stream using Java 8 JDK

In short, you have to use StreamSupport#stream, passing the spliterator, then use map to convert it into string.

Upvotes: 0

Related Questions