How to go through an iterable?

Asked

Viewed 847 times

0

I have a method keysWithPrefix for the purpose of returning all Keys starting with an input value that is specified as in the implementation below:

    public Iterable<String> keysWithPrefix(String pre) {
      Queue<String> q = new Queue<String>() {
      collect(get(root, pre, 0), pre, q);
      return q;
   }
   private void collect(Node x, String pre, Queue<String> q) {
      if (x == null) return;
      if (x.val != null) q.add(pre);
      for (char c = 0; c < R; c++)
         collect(x.next[c], pre + c, q);
   }

But I don’t know how to print the return on the screen. This method returns an Iterable string

2 answers

1

I believe you can do it in two ways;

1st Option

Iterable<String> keys = keysWithPrefix(pre);
Iterator<String> it = keys.iterator();
while(it.hasNext()){
   System.out.println(it.next());
}

2nd Option

Iterable<String> keys = keysWithPrefix(pre);
for(String key: keys){
   System.out.println(key);
}

0

To traverse a Iterable and print your value you can do so:

Iterable<String> iterable = keysWithPrefix(pre);    
Iterable<String> q = iterable.iterator();
//verifica se existe itens a percorrer no Iterable
while(q.hasNext()) {
    //pega um item do Iterable
    String item = q.next();
    System.out.println(item);
}

If you are using java 8 you can do:

Iterable<String> iterable = keysWithPrefix(pre);
//imprime o valor usando o foreach
iterable.foreach(item -> {
    String item = q.next();
    System.out.println(item);
});
//funciona dessa forma também
iterable.foreach(System.out::println);
  • 1

    I believe you’ve mistaken for Iterator

  • I forgot to put the method that calls the iterator, Thanks @Jeffersonquesado, already made the adjustment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.