如何在同一条语句中初始化队列

How to initialize a Queue in the same statement

在数组中,可以通过以下方式在开头添加元素

int[] array = {1,2,3,4,5};

同样如何将多个条目添加到队列中?喜欢,

Queue<Integer> queue = {1,2,3,4,5};

有什么办法吗?

首先,您必须选择要实例化的 Queue 实现。假设您选择 LinkedList(实现 Queue)。

与任何集合一样,LinkedList 有一个构造函数,该构造函数采用 Collection 并将 Collection 的元素添加到列表中。

例如:

Queue<Integer> queue = new LinkedList<>(Arrays.asList(new Integer[]{1,2,3,4,5}));

或(正如 PaulrBear 正确评论的那样):

Queue<Integer> queue = new LinkedList<>(Arrays.asList(1,2,3,4,5));

或者您可以利用 Java 8 个流:

Queue<Integer> queue = IntStream.of(1,2,3,4,5)
                                .boxed()
                                .collect(Collectors.toCollection(LinkedList::new));