How to go through an iterable?

0

I have a keysWithPrefix method for the purpose of returning all keys that start 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 do not know how to print the return on screen. This method returns an Iterable string

    
asked by anonymous 21.01.2018 / 22:49

2 answers

1

I think 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);
}
    
22.01.2018 / 13:05
0

To walk through a Iterable and print its value you can do this:

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);
    
22.01.2018 / 02:00