【问题标题】:How to initialize a Queue in the same statement如何在同一语句中初始化队列
【发布时间】:2015-11-29 14:38:44
【问题描述】:

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

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

类似地,如何将多个条目添加到队列中?喜欢,

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

有什么办法吗?

【问题讨论】:

    标签: java queue abstract-data-type


    【解决方案1】:

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

    与任何 Collection 一样,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 Streams:

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

    【讨论】:

    • 第一种方案可以简化为:Queue queue = new LinkedList(Arrays.asList(1,2,3,4,5));
    • @PaulrBear 你是对的。感谢您的评论。
    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    相关资源
    最近更新 更多