reverseing a queue and converting it into an int array
I have a queue<Integer>
declared as Queue<Integer> queue=new LinkedList();
, I need to reverse the elments order in it, and then convert it into an int array. I wrote below code:
Collections.reverse((List)queue);
int res=queue.stream().mapToInt(Integer::intValue).toArray();
This code has two problems:
- the explict casting
(List)queue
; - I wonder if there is a one line solution.
So do we have any more elegant way to do this?
clearify the problem:
whether the queue is reversed is not important. An int array of the reversed elements is what I need.
java collections queue
add a comment |
I have a queue<Integer>
declared as Queue<Integer> queue=new LinkedList();
, I need to reverse the elments order in it, and then convert it into an int array. I wrote below code:
Collections.reverse((List)queue);
int res=queue.stream().mapToInt(Integer::intValue).toArray();
This code has two problems:
- the explict casting
(List)queue
; - I wonder if there is a one line solution.
So do we have any more elegant way to do this?
clearify the problem:
whether the queue is reversed is not important. An int array of the reversed elements is what I need.
java collections queue
add a comment |
I have a queue<Integer>
declared as Queue<Integer> queue=new LinkedList();
, I need to reverse the elments order in it, and then convert it into an int array. I wrote below code:
Collections.reverse((List)queue);
int res=queue.stream().mapToInt(Integer::intValue).toArray();
This code has two problems:
- the explict casting
(List)queue
; - I wonder if there is a one line solution.
So do we have any more elegant way to do this?
clearify the problem:
whether the queue is reversed is not important. An int array of the reversed elements is what I need.
java collections queue
I have a queue<Integer>
declared as Queue<Integer> queue=new LinkedList();
, I need to reverse the elments order in it, and then convert it into an int array. I wrote below code:
Collections.reverse((List)queue);
int res=queue.stream().mapToInt(Integer::intValue).toArray();
This code has two problems:
- the explict casting
(List)queue
; - I wonder if there is a one line solution.
So do we have any more elegant way to do this?
clearify the problem:
whether the queue is reversed is not important. An int array of the reversed elements is what I need.
java collections queue
java collections queue
edited 1 hour ago
asked 3 hours ago
ZhaoGang
1,6011015
1,6011015
add a comment |
add a comment |
6 Answers
6
active
oldest
votes
The Collections.reverse
implies only to List
which is just one type of Collection
, you cannot cast a Queue
to a List
. But you can try casting it to a LinkedList
as:
Collections.reverse((LinkedList)queue);
Details:
I doubt that there is a built-in API for reversing the queue. You could still follow a conventional way of doing that using a Stack
as :
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.add(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
and then convert to an array as you will
int res = queue.stream().mapToInt(Integer::intValue).toArray();
On the other hand, if a Deque
satisfies your needs currently, you can simply rely on the LinkedList
itself since it implements a Deque
as well. Then your current implementation would be as simple as :
LinkedList<Integer> dequeue = new LinkedList<>();
Collections.reverse(dequeue);
int res = dequeue.stream().mapToInt(Integer::intValue).toArray();
whether the queue is reversed is not important. An int array of the
reversed elements is what I need.
Another solution from what others have already suggested is to reverse the Stream
of the queue
and then mapToInt
to convert to an array as :
Queue<Integer> queue = new LinkedList<>();
int res = reverse(queue.stream()).mapToInt(Integer::intValue).toArray();
This uses a utility reverse
suggested by Stuart Marks in this answer such that:
@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
You should probably not be using theStack
class since it extendsVector
and is therefore synchronized, which is not needed here and only decreases performance.
– Marcono1234
1 hour ago
If using aDeque
it might be more efficient to useDeque.descendingIterator()
combined withSpliterators
andStreamSupport
, assuming only the reversed array is needed and not the reversedDeque
. The code will be more verbose, however.
– Slaw
1 hour ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
add a comment |
In Java8 version you can use Stream API to help you.
The skeleton of code like this:
int reversedQueue = queue.stream()
.collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
.stream().mapToInt(Integer::intValue).toArray();
It looks like your combiner ((a,b)->a
) is missingb
in the result
– Marcono1234
1 hour ago
@Marcono1234 There is no problem.The third parameter ofCollector.of
method is oneBinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.
– TongChen
57 mins ago
add a comment |
First, please don't use raw types (do use the diamond operator). Not quite a one liner, but you could first convert to an int
and then use commons lang ArrayUtils.reverse(int)
like
Queue<Integer> queue = new LinkedList<>();
// ...
int arr = queue.stream().mapToInt(Integer::intValue).toArray();
ArrayUtils.reverse(arr);
You could also write your own int
reverse method that allowed for a fluent interface (e.g. return the int
) then you could make it a one liner. Like,
public static int reverse(int arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
And then
int arr = reverse(queue.stream().mapToInt(Integer::intValue).toArray());
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
2
@nullpointer True. But, if the goal is a reversedint
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and theint
is returned to the caller.
– Elliott Frisch
2 hours ago
add a comment |
This should work with Eclipse Collections
int res = LazyIterate.adapt(queue)
.collectInt(Integer::intValue)
.toList()
.asReversed()
.toArray();
Note: I am a committer for Eclipse Collections.
add a comment |
I think your are right, A raw type should not put in your code. the following is the best I can do.
Integer intArray = queue.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
Collections.reverse(list);
return list;
})).toArray(new Integer[queue.size()]);
add a comment |
This is one line, but it may not be very efficient:
int res = queue.stream()
.collect(LinkedList::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
.stream()
.mapToInt(Integer::intValue)
.toArray();
If you want to be efficient and readable, you should continue using what you have now.
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031994%2freverseing-a-queueinteger-and-converting-it-into-an-int-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
The Collections.reverse
implies only to List
which is just one type of Collection
, you cannot cast a Queue
to a List
. But you can try casting it to a LinkedList
as:
Collections.reverse((LinkedList)queue);
Details:
I doubt that there is a built-in API for reversing the queue. You could still follow a conventional way of doing that using a Stack
as :
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.add(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
and then convert to an array as you will
int res = queue.stream().mapToInt(Integer::intValue).toArray();
On the other hand, if a Deque
satisfies your needs currently, you can simply rely on the LinkedList
itself since it implements a Deque
as well. Then your current implementation would be as simple as :
LinkedList<Integer> dequeue = new LinkedList<>();
Collections.reverse(dequeue);
int res = dequeue.stream().mapToInt(Integer::intValue).toArray();
whether the queue is reversed is not important. An int array of the
reversed elements is what I need.
Another solution from what others have already suggested is to reverse the Stream
of the queue
and then mapToInt
to convert to an array as :
Queue<Integer> queue = new LinkedList<>();
int res = reverse(queue.stream()).mapToInt(Integer::intValue).toArray();
This uses a utility reverse
suggested by Stuart Marks in this answer such that:
@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
You should probably not be using theStack
class since it extendsVector
and is therefore synchronized, which is not needed here and only decreases performance.
– Marcono1234
1 hour ago
If using aDeque
it might be more efficient to useDeque.descendingIterator()
combined withSpliterators
andStreamSupport
, assuming only the reversed array is needed and not the reversedDeque
. The code will be more verbose, however.
– Slaw
1 hour ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
add a comment |
The Collections.reverse
implies only to List
which is just one type of Collection
, you cannot cast a Queue
to a List
. But you can try casting it to a LinkedList
as:
Collections.reverse((LinkedList)queue);
Details:
I doubt that there is a built-in API for reversing the queue. You could still follow a conventional way of doing that using a Stack
as :
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.add(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
and then convert to an array as you will
int res = queue.stream().mapToInt(Integer::intValue).toArray();
On the other hand, if a Deque
satisfies your needs currently, you can simply rely on the LinkedList
itself since it implements a Deque
as well. Then your current implementation would be as simple as :
LinkedList<Integer> dequeue = new LinkedList<>();
Collections.reverse(dequeue);
int res = dequeue.stream().mapToInt(Integer::intValue).toArray();
whether the queue is reversed is not important. An int array of the
reversed elements is what I need.
Another solution from what others have already suggested is to reverse the Stream
of the queue
and then mapToInt
to convert to an array as :
Queue<Integer> queue = new LinkedList<>();
int res = reverse(queue.stream()).mapToInt(Integer::intValue).toArray();
This uses a utility reverse
suggested by Stuart Marks in this answer such that:
@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
You should probably not be using theStack
class since it extendsVector
and is therefore synchronized, which is not needed here and only decreases performance.
– Marcono1234
1 hour ago
If using aDeque
it might be more efficient to useDeque.descendingIterator()
combined withSpliterators
andStreamSupport
, assuming only the reversed array is needed and not the reversedDeque
. The code will be more verbose, however.
– Slaw
1 hour ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
add a comment |
The Collections.reverse
implies only to List
which is just one type of Collection
, you cannot cast a Queue
to a List
. But you can try casting it to a LinkedList
as:
Collections.reverse((LinkedList)queue);
Details:
I doubt that there is a built-in API for reversing the queue. You could still follow a conventional way of doing that using a Stack
as :
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.add(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
and then convert to an array as you will
int res = queue.stream().mapToInt(Integer::intValue).toArray();
On the other hand, if a Deque
satisfies your needs currently, you can simply rely on the LinkedList
itself since it implements a Deque
as well. Then your current implementation would be as simple as :
LinkedList<Integer> dequeue = new LinkedList<>();
Collections.reverse(dequeue);
int res = dequeue.stream().mapToInt(Integer::intValue).toArray();
whether the queue is reversed is not important. An int array of the
reversed elements is what I need.
Another solution from what others have already suggested is to reverse the Stream
of the queue
and then mapToInt
to convert to an array as :
Queue<Integer> queue = new LinkedList<>();
int res = reverse(queue.stream()).mapToInt(Integer::intValue).toArray();
This uses a utility reverse
suggested by Stuart Marks in this answer such that:
@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
The Collections.reverse
implies only to List
which is just one type of Collection
, you cannot cast a Queue
to a List
. But you can try casting it to a LinkedList
as:
Collections.reverse((LinkedList)queue);
Details:
I doubt that there is a built-in API for reversing the queue. You could still follow a conventional way of doing that using a Stack
as :
Stack<Integer> stack = new Stack<>();
while (!queue.isEmpty()) {
stack.add(queue.remove());
}
while (!stack.isEmpty()) {
queue.add(stack.pop());
}
and then convert to an array as you will
int res = queue.stream().mapToInt(Integer::intValue).toArray();
On the other hand, if a Deque
satisfies your needs currently, you can simply rely on the LinkedList
itself since it implements a Deque
as well. Then your current implementation would be as simple as :
LinkedList<Integer> dequeue = new LinkedList<>();
Collections.reverse(dequeue);
int res = dequeue.stream().mapToInt(Integer::intValue).toArray();
whether the queue is reversed is not important. An int array of the
reversed elements is what I need.
Another solution from what others have already suggested is to reverse the Stream
of the queue
and then mapToInt
to convert to an array as :
Queue<Integer> queue = new LinkedList<>();
int res = reverse(queue.stream()).mapToInt(Integer::intValue).toArray();
This uses a utility reverse
suggested by Stuart Marks in this answer such that:
@SuppressWarnings("unchecked")
static <T> Stream<T> reverse(Stream<T> input) {
Object temp = input.toArray();
return (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
}
edited 39 mins ago
answered 2 hours ago
nullpointer
43.1k1093178
43.1k1093178
You should probably not be using theStack
class since it extendsVector
and is therefore synchronized, which is not needed here and only decreases performance.
– Marcono1234
1 hour ago
If using aDeque
it might be more efficient to useDeque.descendingIterator()
combined withSpliterators
andStreamSupport
, assuming only the reversed array is needed and not the reversedDeque
. The code will be more verbose, however.
– Slaw
1 hour ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
add a comment |
You should probably not be using theStack
class since it extendsVector
and is therefore synchronized, which is not needed here and only decreases performance.
– Marcono1234
1 hour ago
If using aDeque
it might be more efficient to useDeque.descendingIterator()
combined withSpliterators
andStreamSupport
, assuming only the reversed array is needed and not the reversedDeque
. The code will be more verbose, however.
– Slaw
1 hour ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
You should probably not be using the
Stack
class since it extends Vector
and is therefore synchronized, which is not needed here and only decreases performance.– Marcono1234
1 hour ago
You should probably not be using the
Stack
class since it extends Vector
and is therefore synchronized, which is not needed here and only decreases performance.– Marcono1234
1 hour ago
If using a
Deque
it might be more efficient to use Deque.descendingIterator()
combined with Spliterators
and StreamSupport
, assuming only the reversed array is needed and not the reversed Deque
. The code will be more verbose, however.– Slaw
1 hour ago
If using a
Deque
it might be more efficient to use Deque.descendingIterator()
combined with Spliterators
and StreamSupport
, assuming only the reversed array is needed and not the reversed Deque
. The code will be more verbose, however.– Slaw
1 hour ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
@Slaw It would be sure. Just that the intention of when I wrote the answer was to ensure the original store is reversed, but later the OP clarified that the reversed output is what matters eventually.
– nullpointer
38 mins ago
add a comment |
In Java8 version you can use Stream API to help you.
The skeleton of code like this:
int reversedQueue = queue.stream()
.collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
.stream().mapToInt(Integer::intValue).toArray();
It looks like your combiner ((a,b)->a
) is missingb
in the result
– Marcono1234
1 hour ago
@Marcono1234 There is no problem.The third parameter ofCollector.of
method is oneBinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.
– TongChen
57 mins ago
add a comment |
In Java8 version you can use Stream API to help you.
The skeleton of code like this:
int reversedQueue = queue.stream()
.collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
.stream().mapToInt(Integer::intValue).toArray();
It looks like your combiner ((a,b)->a
) is missingb
in the result
– Marcono1234
1 hour ago
@Marcono1234 There is no problem.The third parameter ofCollector.of
method is oneBinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.
– TongChen
57 mins ago
add a comment |
In Java8 version you can use Stream API to help you.
The skeleton of code like this:
int reversedQueue = queue.stream()
.collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
.stream().mapToInt(Integer::intValue).toArray();
In Java8 version you can use Stream API to help you.
The skeleton of code like this:
int reversedQueue = queue.stream()
.collect(Collector.of(() -> new ArrayDeque<Integer>(), ArrayDeque::addFirst, (a,b)->a))
.stream().mapToInt(Integer::intValue).toArray();
answered 2 hours ago
TongChen
1857
1857
It looks like your combiner ((a,b)->a
) is missingb
in the result
– Marcono1234
1 hour ago
@Marcono1234 There is no problem.The third parameter ofCollector.of
method is oneBinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.
– TongChen
57 mins ago
add a comment |
It looks like your combiner ((a,b)->a
) is missingb
in the result
– Marcono1234
1 hour ago
@Marcono1234 There is no problem.The third parameter ofCollector.of
method is oneBinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.
– TongChen
57 mins ago
It looks like your combiner (
(a,b)->a
) is missing b
in the result– Marcono1234
1 hour ago
It looks like your combiner (
(a,b)->a
) is missing b
in the result– Marcono1234
1 hour ago
@Marcono1234 There is no problem.The third parameter of
Collector.of
method is one BinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.– TongChen
57 mins ago
@Marcono1234 There is no problem.The third parameter of
Collector.of
method is one BinaryOperator
it's the combiner function for the new collector. In our code there only one collector,so can't miss any element in collector.– TongChen
57 mins ago
add a comment |
First, please don't use raw types (do use the diamond operator). Not quite a one liner, but you could first convert to an int
and then use commons lang ArrayUtils.reverse(int)
like
Queue<Integer> queue = new LinkedList<>();
// ...
int arr = queue.stream().mapToInt(Integer::intValue).toArray();
ArrayUtils.reverse(arr);
You could also write your own int
reverse method that allowed for a fluent interface (e.g. return the int
) then you could make it a one liner. Like,
public static int reverse(int arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
And then
int arr = reverse(queue.stream().mapToInt(Integer::intValue).toArray());
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
2
@nullpointer True. But, if the goal is a reversedint
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and theint
is returned to the caller.
– Elliott Frisch
2 hours ago
add a comment |
First, please don't use raw types (do use the diamond operator). Not quite a one liner, but you could first convert to an int
and then use commons lang ArrayUtils.reverse(int)
like
Queue<Integer> queue = new LinkedList<>();
// ...
int arr = queue.stream().mapToInt(Integer::intValue).toArray();
ArrayUtils.reverse(arr);
You could also write your own int
reverse method that allowed for a fluent interface (e.g. return the int
) then you could make it a one liner. Like,
public static int reverse(int arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
And then
int arr = reverse(queue.stream().mapToInt(Integer::intValue).toArray());
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
2
@nullpointer True. But, if the goal is a reversedint
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and theint
is returned to the caller.
– Elliott Frisch
2 hours ago
add a comment |
First, please don't use raw types (do use the diamond operator). Not quite a one liner, but you could first convert to an int
and then use commons lang ArrayUtils.reverse(int)
like
Queue<Integer> queue = new LinkedList<>();
// ...
int arr = queue.stream().mapToInt(Integer::intValue).toArray();
ArrayUtils.reverse(arr);
You could also write your own int
reverse method that allowed for a fluent interface (e.g. return the int
) then you could make it a one liner. Like,
public static int reverse(int arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
And then
int arr = reverse(queue.stream().mapToInt(Integer::intValue).toArray());
First, please don't use raw types (do use the diamond operator). Not quite a one liner, but you could first convert to an int
and then use commons lang ArrayUtils.reverse(int)
like
Queue<Integer> queue = new LinkedList<>();
// ...
int arr = queue.stream().mapToInt(Integer::intValue).toArray();
ArrayUtils.reverse(arr);
You could also write your own int
reverse method that allowed for a fluent interface (e.g. return the int
) then you could make it a one liner. Like,
public static int reverse(int arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
return arr;
}
And then
int arr = reverse(queue.stream().mapToInt(Integer::intValue).toArray());
answered 2 hours ago
Elliott Frisch
153k1389178
153k1389178
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
2
@nullpointer True. But, if the goal is a reversedint
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and theint
is returned to the caller.
– Elliott Frisch
2 hours ago
add a comment |
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
2
@nullpointer True. But, if the goal is a reversedint
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and theint
is returned to the caller.
– Elliott Frisch
2 hours ago
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
but this wouldn't reverse the queue.
– nullpointer
2 hours ago
2
2
@nullpointer True. But, if the goal is a reversed
int
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int
is returned to the caller.– Elliott Frisch
2 hours ago
@nullpointer True. But, if the goal is a reversed
int
then it isn't clear that the queue must also be reversed. In fact, I would assume the queue goes out of scope and the int
is returned to the caller.– Elliott Frisch
2 hours ago
add a comment |
This should work with Eclipse Collections
int res = LazyIterate.adapt(queue)
.collectInt(Integer::intValue)
.toList()
.asReversed()
.toArray();
Note: I am a committer for Eclipse Collections.
add a comment |
This should work with Eclipse Collections
int res = LazyIterate.adapt(queue)
.collectInt(Integer::intValue)
.toList()
.asReversed()
.toArray();
Note: I am a committer for Eclipse Collections.
add a comment |
This should work with Eclipse Collections
int res = LazyIterate.adapt(queue)
.collectInt(Integer::intValue)
.toList()
.asReversed()
.toArray();
Note: I am a committer for Eclipse Collections.
This should work with Eclipse Collections
int res = LazyIterate.adapt(queue)
.collectInt(Integer::intValue)
.toList()
.asReversed()
.toArray();
Note: I am a committer for Eclipse Collections.
answered 44 mins ago
Donald Raab
4,21112029
4,21112029
add a comment |
add a comment |
I think your are right, A raw type should not put in your code. the following is the best I can do.
Integer intArray = queue.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
Collections.reverse(list);
return list;
})).toArray(new Integer[queue.size()]);
add a comment |
I think your are right, A raw type should not put in your code. the following is the best I can do.
Integer intArray = queue.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
Collections.reverse(list);
return list;
})).toArray(new Integer[queue.size()]);
add a comment |
I think your are right, A raw type should not put in your code. the following is the best I can do.
Integer intArray = queue.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
Collections.reverse(list);
return list;
})).toArray(new Integer[queue.size()]);
I think your are right, A raw type should not put in your code. the following is the best I can do.
Integer intArray = queue.stream().collect(Collectors.collectingAndThen(Collectors.toList(), list -> {
Collections.reverse(list);
return list;
})).toArray(new Integer[queue.size()]);
edited 2 hours ago
answered 2 hours ago
Keijack
1466
1466
add a comment |
add a comment |
This is one line, but it may not be very efficient:
int res = queue.stream()
.collect(LinkedList::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
.stream()
.mapToInt(Integer::intValue)
.toArray();
If you want to be efficient and readable, you should continue using what you have now.
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
add a comment |
This is one line, but it may not be very efficient:
int res = queue.stream()
.collect(LinkedList::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
.stream()
.mapToInt(Integer::intValue)
.toArray();
If you want to be efficient and readable, you should continue using what you have now.
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
add a comment |
This is one line, but it may not be very efficient:
int res = queue.stream()
.collect(LinkedList::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
.stream()
.mapToInt(Integer::intValue)
.toArray();
If you want to be efficient and readable, you should continue using what you have now.
This is one line, but it may not be very efficient:
int res = queue.stream()
.collect(LinkedList::new, (l, e) -> l.addFirst(e), (l1, l2) -> l1.addAll(l2))
.stream()
.mapToInt(Integer::intValue)
.toArray();
If you want to be efficient and readable, you should continue using what you have now.
edited 5 mins ago
answered 2 hours ago
Jai
5,72411231
5,72411231
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
add a comment |
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
This does not reverse the queue (or its values)
– Marcono1234
1 hour ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
@Marcono1234 Thanks for pointing out.
– Jai
5 mins ago
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54031994%2freverseing-a-queueinteger-and-converting-it-into-an-int-array%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown