Bootstrap

Java Queue的遍历

Queue<Integer> queue = new LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);

------------------Queue的遍历方式-----------------------
# for + poll
int len = queue.size();
for (int i = 0; i < len; i++) {
    System.out.print(queue.poll());
}

# while + poll
while (!queue.isEmpty()) {
    System.out.println(queue.poll());
}

------------------List的遍历方式-----------------------
# 增强 for 循环
for (Integer e : queue) {
    System.out.println(e);
}

# for 迭代器
for (Iterator<Integer> it = queue.iterator(); it.hasNext(); ) {
    Integer element = it.next();
    System.out.println(element);
}

# while 迭代器
Iterator<Integer> iterator = queue.iterator();
while (iterator.hasNext()) {
    Integer element = iterator.next();
    System.out.println(element);
}

# list.forEach 循环
queue.forEach(a -> System.out.print(a)); // 123

# list.stream().forEach 循环
queue.stream().forEach(a -> System.out.print(a)); // 123

# list.parallelStream().forEach 循环
queue.parallelStream().forEach(a -> System.out.print(a)); // 231 有可能乱序

# 转为List
List<Integer> list = new ArrayList<>(queue);

------------------数组的遍历方式-----------------------
# 转为数组
Integer[] arr = queue.toArray(Integer[]::new);
;