Hello to all! How can I iterate through all the elements of Deque and Queue as in an array?
2 answers
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); } |