Hello to all! How can I iterate through all the elements of Deque and Queue as in an array?

  • And why is it necessary? - post_zeew
  • And what's the problem then? - Mikhail Chibel

2 answers 2

Queue<Integer> q = new ArrayDeque<>(Arrays.asList(11, 33, 55, 22, 44)); //#1 for-each q.forEach(System.out::println); //#2 итСрация "ΠΊΠ°ΠΊ Π² массивС" с i Iterator<Integer> iterator = q.iterator(); for (int i = 0; ; ++i) { if (iterator.hasNext()) { Integer value = iterator.next(); System.out.println(i + " " + value); } else break; } //#3 итСрация "ΠΊΠ°ΠΊ Π² настоящСм массивС" List<Integer> integers = new ArrayList<>(q); for (int i = 0, max = integers.size(); i < max; i++) { System.out.println(i + " " + integers.get(i)); } 

Result:

 11 33 55 22 44 0 11 1 33 2 55 3 22 4 44 

    The Queue and Deque interfaces extend the Collection interface; therefore, all elements can be Deque as in any collection using the extended for loop:

     void enumerateQueue(Queue<T> queue) { for(T t : queue) { // здСсь ΠΌΠΎΠΆΠ½ΠΎ Π΄Π΅Π»Π°Ρ‚ΡŒ Ρ‡Ρ‚ΠΎ ΡƒΠ³ΠΎΠ΄Π½ΠΎ с ΠΎΡ‡Π΅Ρ€Π΅Π΄Π½Ρ‹ΠΌ элСмСнтом ΠΊΠΎΠ»Π»Π΅ΠΊΡ†ΠΈΠΈ System.out.println(t); } } 

    Like any collection, Queue and Deque have a stream() method that allows you to Deque through elements using the Stream API:

     void queueAsStream(Queue<T> queue) { queue.stream().forEach(System.out::println); }