1

In arrays, elements can be added at the beginning in the following manner

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

similarly how to add multiple entries to a Queue? like,

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

is there any way to do this?

1 Answer 1

4

First you must choose which Queue implementation you wish to instantiate. Let's assume you are choosing LinkedList (which implements Queue).

Like any Collection, LinkedList has a constructor that takes a Collection and adds the elements of that Collection to the list.

For example:

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

or (as PaulrBear correctly commented):

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

Or you can take advantage of Java 8 Streams :

Queue<Integer> queue = IntStream.of(1,2,3,4,5)
                                .boxed()
                                .collect(Collectors.toCollection(LinkedList::new));
Sign up to request clarification or add additional context in comments.

2 Comments

The first solution can be simplified to: Queue<Integer> queue = new LinkedList<>(Arrays.asList(1,2,3,4,5));
@PaulrBear You are correct. Thanks for the comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.