How to iterate over a queue in Java

4 Answers

0 votes
import java.util.LinkedList; 
import java.util.Queue; 
 
public class MyClass {
    public static void main(String args[]) { 
        Queue<Integer> queue = new LinkedList<Integer>();
         
        queue.add(4); 
        queue.add(6); 
        queue.add(3); 
        queue.add(7); 
        queue.add(2); 

        for (Integer item: queue) {
            System.out.println(item);
        }
    }
}
 
 
 
 
/*
run:
 
4
6
3
7
2

*/

 



answered Mar 16, 2023 by avibootz
0 votes
import java.util.LinkedList; 
import java.util.Iterator;
import java.util.Queue; 

public class MyClass {
    public static void main(String args[]) { 
        Queue<Integer> queue = new LinkedList<Integer>();
         
        queue.add(4); 
        queue.add(6); 
        queue.add(3); 
        queue.add(7); 
        queue.add(2); 

        Iterator<Integer> it = queue.iterator();
 
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}
 
 
 
 
/*
run:
 
4
6
3
7
2

*/

 



answered Mar 16, 2023 by avibootz
0 votes
import java.util.LinkedList; 
import java.util.Queue; 

public class MyClass {
    public static void main(String args[]) { 
        Queue<Integer> queue = new LinkedList<Integer>();
         
        queue.add(4); 
        queue.add(6); 
        queue.add(3); 
        queue.add(7); 
        queue.add(2); 

        queue.stream().forEach(n -> {
            System.out.println(n);
        });
    }
}
 
 
 
 
/*
run:
 
4
6
3
7
2

*/

 



answered Mar 16, 2023 by avibootz
0 votes
import java.util.LinkedList; 
import java.util.Queue; 

public class MyClass {
    public static void main(String args[]) { 
        Queue<Integer> queue = new LinkedList<Integer>();
         
        queue.add(4); 
        queue.add(6); 
        queue.add(3); 
        queue.add(7); 
        queue.add(2); 

        queue.stream().forEach(System.out::println);
    }
}
 
 
 
 
/*
run:
 
4
6
3
7
2

*/

 



answered Mar 16, 2023 by avibootz

Related questions

4 answers 173 views
173 views asked Nov 23, 2023 by avibootz
2 answers 203 views
1 answer 130 views
1 answer 135 views
2 answers 118 views
118 views asked Mar 15, 2023 by avibootz
...