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?
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));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.