How to sort integer array in ascending and descending order using lambda only in java
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
int arr2 = new int {54, 432, 53, 21, 43};
I am using this to sort but it is giving an error.
Arrays.sort(arr2, (a, b) -> a - b);
This is also giving an error.
arr2.sort((a, b) -> a - b);
java arrays lambda java-8 java-stream
add a comment |
int arr2 = new int {54, 432, 53, 21, 43};
I am using this to sort but it is giving an error.
Arrays.sort(arr2, (a, b) -> a - b);
This is also giving an error.
arr2.sort((a, b) -> a - b);
java arrays lambda java-8 java-stream
7
Never use a comparator like(a,b)->a-b
forint
values. It may work in some use cases, but the difference between twoint
values may be bigger than theint
value range and cause overflows. Therefore, use(a,b) -> Integer.compare(a, b)
resp.Integer::compare
. To reverse the order, use(a,b) -> Integer.compare(b, a)
. Do not negate the value returned by a compare function, that will fail if the value isInteger.MIN_VALUE
.
– Holger
Jan 10 at 11:15
4
"giving error" what error? Please specify this information.
– Ian Kemp
Jan 10 at 11:25
2
@IanKemp in this case, it’s obvious enough. Arrays don’t have asort
method and thesort(T a, Comparator<? super T> c)
method does not support primitive type arrays.
– Holger
Jan 10 at 11:30
3
@Holger Whether it's obvious enough is irrelevant - the rules specify that a question must include a specific problem or error. "Giving error" is the same as saying "doesn't work", which is not helpful to anyone - especially not people who might be looking for the specific error caused by using a comparator like(a,b)->a-b
withInteger.MIN_VALUE
.
– Ian Kemp
Jan 10 at 11:59
2
@Holger Thank you for continuing the battle to eradicate subtraction as a means to compare two int values.
– Stuart Marks
Jan 10 at 18:52
add a comment |
int arr2 = new int {54, 432, 53, 21, 43};
I am using this to sort but it is giving an error.
Arrays.sort(arr2, (a, b) -> a - b);
This is also giving an error.
arr2.sort((a, b) -> a - b);
java arrays lambda java-8 java-stream
int arr2 = new int {54, 432, 53, 21, 43};
I am using this to sort but it is giving an error.
Arrays.sort(arr2, (a, b) -> a - b);
This is also giving an error.
arr2.sort((a, b) -> a - b);
java arrays lambda java-8 java-stream
java arrays lambda java-8 java-stream
edited Jan 10 at 18:46
Nicholas K
8,54071739
8,54071739
asked Jan 10 at 10:45
WhiteWalkerWhiteWalker
536
536
7
Never use a comparator like(a,b)->a-b
forint
values. It may work in some use cases, but the difference between twoint
values may be bigger than theint
value range and cause overflows. Therefore, use(a,b) -> Integer.compare(a, b)
resp.Integer::compare
. To reverse the order, use(a,b) -> Integer.compare(b, a)
. Do not negate the value returned by a compare function, that will fail if the value isInteger.MIN_VALUE
.
– Holger
Jan 10 at 11:15
4
"giving error" what error? Please specify this information.
– Ian Kemp
Jan 10 at 11:25
2
@IanKemp in this case, it’s obvious enough. Arrays don’t have asort
method and thesort(T a, Comparator<? super T> c)
method does not support primitive type arrays.
– Holger
Jan 10 at 11:30
3
@Holger Whether it's obvious enough is irrelevant - the rules specify that a question must include a specific problem or error. "Giving error" is the same as saying "doesn't work", which is not helpful to anyone - especially not people who might be looking for the specific error caused by using a comparator like(a,b)->a-b
withInteger.MIN_VALUE
.
– Ian Kemp
Jan 10 at 11:59
2
@Holger Thank you for continuing the battle to eradicate subtraction as a means to compare two int values.
– Stuart Marks
Jan 10 at 18:52
add a comment |
7
Never use a comparator like(a,b)->a-b
forint
values. It may work in some use cases, but the difference between twoint
values may be bigger than theint
value range and cause overflows. Therefore, use(a,b) -> Integer.compare(a, b)
resp.Integer::compare
. To reverse the order, use(a,b) -> Integer.compare(b, a)
. Do not negate the value returned by a compare function, that will fail if the value isInteger.MIN_VALUE
.
– Holger
Jan 10 at 11:15
4
"giving error" what error? Please specify this information.
– Ian Kemp
Jan 10 at 11:25
2
@IanKemp in this case, it’s obvious enough. Arrays don’t have asort
method and thesort(T a, Comparator<? super T> c)
method does not support primitive type arrays.
– Holger
Jan 10 at 11:30
3
@Holger Whether it's obvious enough is irrelevant - the rules specify that a question must include a specific problem or error. "Giving error" is the same as saying "doesn't work", which is not helpful to anyone - especially not people who might be looking for the specific error caused by using a comparator like(a,b)->a-b
withInteger.MIN_VALUE
.
– Ian Kemp
Jan 10 at 11:59
2
@Holger Thank you for continuing the battle to eradicate subtraction as a means to compare two int values.
– Stuart Marks
Jan 10 at 18:52
7
7
Never use a comparator like
(a,b)->a-b
for int
values. It may work in some use cases, but the difference between two int
values may be bigger than the int
value range and cause overflows. Therefore, use (a,b) -> Integer.compare(a, b)
resp. Integer::compare
. To reverse the order, use (a,b) -> Integer.compare(b, a)
. Do not negate the value returned by a compare function, that will fail if the value is Integer.MIN_VALUE
.– Holger
Jan 10 at 11:15
Never use a comparator like
(a,b)->a-b
for int
values. It may work in some use cases, but the difference between two int
values may be bigger than the int
value range and cause overflows. Therefore, use (a,b) -> Integer.compare(a, b)
resp. Integer::compare
. To reverse the order, use (a,b) -> Integer.compare(b, a)
. Do not negate the value returned by a compare function, that will fail if the value is Integer.MIN_VALUE
.– Holger
Jan 10 at 11:15
4
4
"giving error" what error? Please specify this information.
– Ian Kemp
Jan 10 at 11:25
"giving error" what error? Please specify this information.
– Ian Kemp
Jan 10 at 11:25
2
2
@IanKemp in this case, it’s obvious enough. Arrays don’t have a
sort
method and the sort(T a, Comparator<? super T> c)
method does not support primitive type arrays.– Holger
Jan 10 at 11:30
@IanKemp in this case, it’s obvious enough. Arrays don’t have a
sort
method and the sort(T a, Comparator<? super T> c)
method does not support primitive type arrays.– Holger
Jan 10 at 11:30
3
3
@Holger Whether it's obvious enough is irrelevant - the rules specify that a question must include a specific problem or error. "Giving error" is the same as saying "doesn't work", which is not helpful to anyone - especially not people who might be looking for the specific error caused by using a comparator like
(a,b)->a-b
with Integer.MIN_VALUE
.– Ian Kemp
Jan 10 at 11:59
@Holger Whether it's obvious enough is irrelevant - the rules specify that a question must include a specific problem or error. "Giving error" is the same as saying "doesn't work", which is not helpful to anyone - especially not people who might be looking for the specific error caused by using a comparator like
(a,b)->a-b
with Integer.MIN_VALUE
.– Ian Kemp
Jan 10 at 11:59
2
2
@Holger Thank you for continuing the battle to eradicate subtraction as a means to compare two int values.
– Stuart Marks
Jan 10 at 18:52
@Holger Thank you for continuing the battle to eradicate subtraction as a means to compare two int values.
– Stuart Marks
Jan 10 at 18:52
add a comment |
6 Answers
6
active
oldest
votes
Given
int array = ... ;
To sort ascending, simply do
Arrays.sort(array);
Here's a pretty way to sort descending:
Arrays.setAll(array, i -> ~array[i]);
Arrays.sort(array);
Arrays.setAll(array, i -> ~array[i]);
This is a tiny bit slower than sorting ascending and then reversing the array; it has to do an extra pass over the array. The runtime is dominated by the sorting for an array of any significant size, so it's unlikely to be noticeable.
This works by doing a bitwise complement of the int values before and after the sort. This provides an exact, lossless reversal of the ordering of every possible int value. To see this, you have to understand that Java ints use two's complement representation. Consider if ints were to have only three bits. All the values would be as follows:
100 101 110 111 000 001 010 011
-4 -3 -2 -1 0 1 2 3
MIN_VALUE ^
The bitwise complement operator ~
inverts every bit. You can see by inspection that this reflects the table about a pivot point between -1 and 0, so -4 becomes 3, -3 becomes 2, etc. Also, another complement will restore the original value. Thus, an ascending sort on the complemented values is a descending sort on the original values.
Note that this differs from negation -
which doesn't do the right thing here. It reflects the table at zero, so the negation of zero is zero, the negation of -1 is 1, etc. This is asymmetric, because the negation of MIN_VALUE is MIN_VALUE. Thus, using negation in an attempt to perform a descending sort doesn't work.
Finally, boxing and using a Comparator works, but it's considerably slower, and it allocates a separate object for (almost) every int value. I recommend avoiding boxing.
1
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
2
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
add a comment |
You could sort the input of type Integer
as :
Integer arr2 = new Integer {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
or possibly with primitive types as :
int arr2 = new int{54, 432, 53, 21, 43};
int sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();
or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :
int sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();
Edit: For an in-place ascending order sort, you just need to perform :
int arr2 = new int{54, 432, 53, 21, 43};
Arrays.sort(arr2);
1
For ascending order, you can useArrays.stream(arr2).sorted().toArray()
or just sort in-place withArrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences ofInteger.MIN_VALUE
are among the values.
– Holger
Jan 10 at 11:19
@Holger true, that's what I meant in the note before themap.sort.map
solution about boundary values.
– Naman
Jan 10 at 11:21
2
As explained in Stuart Marks’ answer, using binary not (~
) instead of minus (-
) would solve the issue withInteger.MIN_VALUE
.
– Holger
Jan 11 at 8:29
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
add a comment |
Sort in ascending order :
int ascArr = Arrays.stream(arr2).boxed().sorted(Comparator.naturalOrder())
.mapToInt(Integer::intValue).toArray();
int ascArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(a, b))
.mapToInt(Integer::intValue).toArray();
int ascArr = Arrays.stream(arr2).sorted().toArray();
Sort in descending order :
int descArr = Arrays.stream(arr2).boxed().sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue).toArray();
int descArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(b, a))
.mapToInt(Integer::intValue).toArray();
add a comment |
There are different ways to create a sorted array of int
s out of an unsorted one using streams, as the other answers show. These approaches have the disadvantage of either requiring boxing/unboxing (so that a Comparator<Integer>
can be used), or that new arrays are needed to accommodate the elements.
Here's a way to sort in-place without boxing/unboxing. First, in ascending order:
int arr2 = ...
Arrays.sort(arr2);
Unfortunately, there's no way to sort in-place in descending order using a single-line operation. You will need to sort ascending first, then reverse the array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
for (int left = 0; left < size / 2; left++) {
int right = size - i - 1;
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
EDIT: As @Holger points out in the comments, the for
loop above could be improved as follows:
for (int left = 0, right = arr2.length - 1; left < right; left++, right--) {
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
An alternative is to sort in ascending order and then place the elements in reverse order into a new array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
int reversed = new int[size];
Arrays.setAll(reversed, i -> arr2[size - i - 1]);
This uses Arrays.setAll
to accomplish the task.
1
You may consider a simplerfor(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.
– Holger
Jan 11 at 8:05
add a comment |
If you explicitly need a custom comparator lambda, try this one:
int arr2 = new int {54,432,53,21,43};
int arr3 = IntStream.of(arr2).boxed().sorted((a, b) -> a - b).mapToInt(Integer::intValue).toArray();
add a comment |
public class lambdaTest {
public static void main(String args) {
int arr2 = new int {54,432,53,21,43};
int sorted = IntStream.of(arr2)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
System.out.println("In decending Order:");
for(int ss : sorted)
{
System.out.print(ss+", ");
}
System.out.println();
int reversed = IntStream.range(0, sorted.length)
.map(i -> sorted[sorted.length-i-1])
.toArray();
System.out.println("In Ascending Order: ");
for(int ss1 : reversed)
{
System.out.print(ss1+", ");
}
}
}
OUTPUT
In decending Order:
432, 54, 53, 43, 21,
In Ascending Order:
21, 43, 53, 54, 432,
Edit: much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray())
Thanks to Holger
1
It would be much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.
– Holger
Jan 10 at 11:23
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
1
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using aComparator
).
– Holger
Jan 10 at 11:27
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
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%2f54126952%2fhow-to-sort-integer-array-in-ascending-and-descending-order-using-lambda-only-in%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
Given
int array = ... ;
To sort ascending, simply do
Arrays.sort(array);
Here's a pretty way to sort descending:
Arrays.setAll(array, i -> ~array[i]);
Arrays.sort(array);
Arrays.setAll(array, i -> ~array[i]);
This is a tiny bit slower than sorting ascending and then reversing the array; it has to do an extra pass over the array. The runtime is dominated by the sorting for an array of any significant size, so it's unlikely to be noticeable.
This works by doing a bitwise complement of the int values before and after the sort. This provides an exact, lossless reversal of the ordering of every possible int value. To see this, you have to understand that Java ints use two's complement representation. Consider if ints were to have only three bits. All the values would be as follows:
100 101 110 111 000 001 010 011
-4 -3 -2 -1 0 1 2 3
MIN_VALUE ^
The bitwise complement operator ~
inverts every bit. You can see by inspection that this reflects the table about a pivot point between -1 and 0, so -4 becomes 3, -3 becomes 2, etc. Also, another complement will restore the original value. Thus, an ascending sort on the complemented values is a descending sort on the original values.
Note that this differs from negation -
which doesn't do the right thing here. It reflects the table at zero, so the negation of zero is zero, the negation of -1 is 1, etc. This is asymmetric, because the negation of MIN_VALUE is MIN_VALUE. Thus, using negation in an attempt to perform a descending sort doesn't work.
Finally, boxing and using a Comparator works, but it's considerably slower, and it allocates a separate object for (almost) every int value. I recommend avoiding boxing.
1
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
2
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
add a comment |
Given
int array = ... ;
To sort ascending, simply do
Arrays.sort(array);
Here's a pretty way to sort descending:
Arrays.setAll(array, i -> ~array[i]);
Arrays.sort(array);
Arrays.setAll(array, i -> ~array[i]);
This is a tiny bit slower than sorting ascending and then reversing the array; it has to do an extra pass over the array. The runtime is dominated by the sorting for an array of any significant size, so it's unlikely to be noticeable.
This works by doing a bitwise complement of the int values before and after the sort. This provides an exact, lossless reversal of the ordering of every possible int value. To see this, you have to understand that Java ints use two's complement representation. Consider if ints were to have only three bits. All the values would be as follows:
100 101 110 111 000 001 010 011
-4 -3 -2 -1 0 1 2 3
MIN_VALUE ^
The bitwise complement operator ~
inverts every bit. You can see by inspection that this reflects the table about a pivot point between -1 and 0, so -4 becomes 3, -3 becomes 2, etc. Also, another complement will restore the original value. Thus, an ascending sort on the complemented values is a descending sort on the original values.
Note that this differs from negation -
which doesn't do the right thing here. It reflects the table at zero, so the negation of zero is zero, the negation of -1 is 1, etc. This is asymmetric, because the negation of MIN_VALUE is MIN_VALUE. Thus, using negation in an attempt to perform a descending sort doesn't work.
Finally, boxing and using a Comparator works, but it's considerably slower, and it allocates a separate object for (almost) every int value. I recommend avoiding boxing.
1
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
2
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
add a comment |
Given
int array = ... ;
To sort ascending, simply do
Arrays.sort(array);
Here's a pretty way to sort descending:
Arrays.setAll(array, i -> ~array[i]);
Arrays.sort(array);
Arrays.setAll(array, i -> ~array[i]);
This is a tiny bit slower than sorting ascending and then reversing the array; it has to do an extra pass over the array. The runtime is dominated by the sorting for an array of any significant size, so it's unlikely to be noticeable.
This works by doing a bitwise complement of the int values before and after the sort. This provides an exact, lossless reversal of the ordering of every possible int value. To see this, you have to understand that Java ints use two's complement representation. Consider if ints were to have only three bits. All the values would be as follows:
100 101 110 111 000 001 010 011
-4 -3 -2 -1 0 1 2 3
MIN_VALUE ^
The bitwise complement operator ~
inverts every bit. You can see by inspection that this reflects the table about a pivot point between -1 and 0, so -4 becomes 3, -3 becomes 2, etc. Also, another complement will restore the original value. Thus, an ascending sort on the complemented values is a descending sort on the original values.
Note that this differs from negation -
which doesn't do the right thing here. It reflects the table at zero, so the negation of zero is zero, the negation of -1 is 1, etc. This is asymmetric, because the negation of MIN_VALUE is MIN_VALUE. Thus, using negation in an attempt to perform a descending sort doesn't work.
Finally, boxing and using a Comparator works, but it's considerably slower, and it allocates a separate object for (almost) every int value. I recommend avoiding boxing.
Given
int array = ... ;
To sort ascending, simply do
Arrays.sort(array);
Here's a pretty way to sort descending:
Arrays.setAll(array, i -> ~array[i]);
Arrays.sort(array);
Arrays.setAll(array, i -> ~array[i]);
This is a tiny bit slower than sorting ascending and then reversing the array; it has to do an extra pass over the array. The runtime is dominated by the sorting for an array of any significant size, so it's unlikely to be noticeable.
This works by doing a bitwise complement of the int values before and after the sort. This provides an exact, lossless reversal of the ordering of every possible int value. To see this, you have to understand that Java ints use two's complement representation. Consider if ints were to have only three bits. All the values would be as follows:
100 101 110 111 000 001 010 011
-4 -3 -2 -1 0 1 2 3
MIN_VALUE ^
The bitwise complement operator ~
inverts every bit. You can see by inspection that this reflects the table about a pivot point between -1 and 0, so -4 becomes 3, -3 becomes 2, etc. Also, another complement will restore the original value. Thus, an ascending sort on the complemented values is a descending sort on the original values.
Note that this differs from negation -
which doesn't do the right thing here. It reflects the table at zero, so the negation of zero is zero, the negation of -1 is 1, etc. This is asymmetric, because the negation of MIN_VALUE is MIN_VALUE. Thus, using negation in an attempt to perform a descending sort doesn't work.
Finally, boxing and using a Comparator works, but it's considerably slower, and it allocates a separate object for (almost) every int value. I recommend avoiding boxing.
answered Jan 11 at 2:19
Stuart MarksStuart Marks
84.2k26138210
84.2k26138210
1
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
2
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
add a comment |
1
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
2
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
1
1
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
Hi! Wouldn't the fact that you need to do all this work with the bits mean that a new method is needed? i.e. Arrays.sortDescending
– Federico Peralta Schaffner
Jan 11 at 11:09
2
2
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
@FedericoPeraltaSchaffner Quite possibly. It might be useful to add some primitive array operations. This does seem to be a frequently asked question, and common answers (such as those that involve boxing) perform quite poorly.
– Stuart Marks
Jan 11 at 16:22
add a comment |
You could sort the input of type Integer
as :
Integer arr2 = new Integer {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
or possibly with primitive types as :
int arr2 = new int{54, 432, 53, 21, 43};
int sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();
or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :
int sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();
Edit: For an in-place ascending order sort, you just need to perform :
int arr2 = new int{54, 432, 53, 21, 43};
Arrays.sort(arr2);
1
For ascending order, you can useArrays.stream(arr2).sorted().toArray()
or just sort in-place withArrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences ofInteger.MIN_VALUE
are among the values.
– Holger
Jan 10 at 11:19
@Holger true, that's what I meant in the note before themap.sort.map
solution about boundary values.
– Naman
Jan 10 at 11:21
2
As explained in Stuart Marks’ answer, using binary not (~
) instead of minus (-
) would solve the issue withInteger.MIN_VALUE
.
– Holger
Jan 11 at 8:29
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
add a comment |
You could sort the input of type Integer
as :
Integer arr2 = new Integer {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
or possibly with primitive types as :
int arr2 = new int{54, 432, 53, 21, 43};
int sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();
or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :
int sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();
Edit: For an in-place ascending order sort, you just need to perform :
int arr2 = new int{54, 432, 53, 21, 43};
Arrays.sort(arr2);
1
For ascending order, you can useArrays.stream(arr2).sorted().toArray()
or just sort in-place withArrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences ofInteger.MIN_VALUE
are among the values.
– Holger
Jan 10 at 11:19
@Holger true, that's what I meant in the note before themap.sort.map
solution about boundary values.
– Naman
Jan 10 at 11:21
2
As explained in Stuart Marks’ answer, using binary not (~
) instead of minus (-
) would solve the issue withInteger.MIN_VALUE
.
– Holger
Jan 11 at 8:29
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
add a comment |
You could sort the input of type Integer
as :
Integer arr2 = new Integer {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
or possibly with primitive types as :
int arr2 = new int{54, 432, 53, 21, 43};
int sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();
or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :
int sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();
Edit: For an in-place ascending order sort, you just need to perform :
int arr2 = new int{54, 432, 53, 21, 43};
Arrays.sort(arr2);
You could sort the input of type Integer
as :
Integer arr2 = new Integer {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
or possibly with primitive types as :
int arr2 = new int{54, 432, 53, 21, 43};
int sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();
or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :
int sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();
Edit: For an in-place ascending order sort, you just need to perform :
int arr2 = new int{54, 432, 53, 21, 43};
Arrays.sort(arr2);
edited Jan 11 at 8:39
answered Jan 10 at 10:47
NamanNaman
45.7k11102204
45.7k11102204
1
For ascending order, you can useArrays.stream(arr2).sorted().toArray()
or just sort in-place withArrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences ofInteger.MIN_VALUE
are among the values.
– Holger
Jan 10 at 11:19
@Holger true, that's what I meant in the note before themap.sort.map
solution about boundary values.
– Naman
Jan 10 at 11:21
2
As explained in Stuart Marks’ answer, using binary not (~
) instead of minus (-
) would solve the issue withInteger.MIN_VALUE
.
– Holger
Jan 11 at 8:29
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
add a comment |
1
For ascending order, you can useArrays.stream(arr2).sorted().toArray()
or just sort in-place withArrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences ofInteger.MIN_VALUE
are among the values.
– Holger
Jan 10 at 11:19
@Holger true, that's what I meant in the note before themap.sort.map
solution about boundary values.
– Naman
Jan 10 at 11:21
2
As explained in Stuart Marks’ answer, using binary not (~
) instead of minus (-
) would solve the issue withInteger.MIN_VALUE
.
– Holger
Jan 11 at 8:29
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
1
1
For ascending order, you can use
Arrays.stream(arr2).sorted().toArray()
or just sort in-place with Arrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences of Integer.MIN_VALUE
are among the values.– Holger
Jan 10 at 11:19
For ascending order, you can use
Arrays.stream(arr2).sorted().toArray()
or just sort in-place with Arrays.sort(arr2)
. However, be aware that the trick with negating the values does not work if one or more occurrences of Integer.MIN_VALUE
are among the values.– Holger
Jan 10 at 11:19
@Holger true, that's what I meant in the note before the
map.sort.map
solution about boundary values.– Naman
Jan 10 at 11:21
@Holger true, that's what I meant in the note before the
map.sort.map
solution about boundary values.– Naman
Jan 10 at 11:21
2
2
As explained in Stuart Marks’ answer, using binary not (
~
) instead of minus (-
) would solve the issue with Integer.MIN_VALUE
.– Holger
Jan 11 at 8:29
As explained in Stuart Marks’ answer, using binary not (
~
) instead of minus (-
) would solve the issue with Integer.MIN_VALUE
.– Holger
Jan 11 at 8:29
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
@Holger Thanks for sharing. Would spend some time reading Stuart's answer later for sure.
– Naman
Jan 11 at 8:40
add a comment |
Sort in ascending order :
int ascArr = Arrays.stream(arr2).boxed().sorted(Comparator.naturalOrder())
.mapToInt(Integer::intValue).toArray();
int ascArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(a, b))
.mapToInt(Integer::intValue).toArray();
int ascArr = Arrays.stream(arr2).sorted().toArray();
Sort in descending order :
int descArr = Arrays.stream(arr2).boxed().sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue).toArray();
int descArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(b, a))
.mapToInt(Integer::intValue).toArray();
add a comment |
Sort in ascending order :
int ascArr = Arrays.stream(arr2).boxed().sorted(Comparator.naturalOrder())
.mapToInt(Integer::intValue).toArray();
int ascArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(a, b))
.mapToInt(Integer::intValue).toArray();
int ascArr = Arrays.stream(arr2).sorted().toArray();
Sort in descending order :
int descArr = Arrays.stream(arr2).boxed().sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue).toArray();
int descArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(b, a))
.mapToInt(Integer::intValue).toArray();
add a comment |
Sort in ascending order :
int ascArr = Arrays.stream(arr2).boxed().sorted(Comparator.naturalOrder())
.mapToInt(Integer::intValue).toArray();
int ascArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(a, b))
.mapToInt(Integer::intValue).toArray();
int ascArr = Arrays.stream(arr2).sorted().toArray();
Sort in descending order :
int descArr = Arrays.stream(arr2).boxed().sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue).toArray();
int descArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(b, a))
.mapToInt(Integer::intValue).toArray();
Sort in ascending order :
int ascArr = Arrays.stream(arr2).boxed().sorted(Comparator.naturalOrder())
.mapToInt(Integer::intValue).toArray();
int ascArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(a, b))
.mapToInt(Integer::intValue).toArray();
int ascArr = Arrays.stream(arr2).sorted().toArray();
Sort in descending order :
int descArr = Arrays.stream(arr2).boxed().sorted(Comparator.reverseOrder())
.mapToInt(Integer::intValue).toArray();
int descArr = IntStream.of(arr2).boxed().sorted((a, b) -> Integer.compare(b, a))
.mapToInt(Integer::intValue).toArray();
edited Jan 12 at 5:51
answered Jan 10 at 10:59
Nicholas KNicholas K
8,54071739
8,54071739
add a comment |
add a comment |
There are different ways to create a sorted array of int
s out of an unsorted one using streams, as the other answers show. These approaches have the disadvantage of either requiring boxing/unboxing (so that a Comparator<Integer>
can be used), or that new arrays are needed to accommodate the elements.
Here's a way to sort in-place without boxing/unboxing. First, in ascending order:
int arr2 = ...
Arrays.sort(arr2);
Unfortunately, there's no way to sort in-place in descending order using a single-line operation. You will need to sort ascending first, then reverse the array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
for (int left = 0; left < size / 2; left++) {
int right = size - i - 1;
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
EDIT: As @Holger points out in the comments, the for
loop above could be improved as follows:
for (int left = 0, right = arr2.length - 1; left < right; left++, right--) {
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
An alternative is to sort in ascending order and then place the elements in reverse order into a new array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
int reversed = new int[size];
Arrays.setAll(reversed, i -> arr2[size - i - 1]);
This uses Arrays.setAll
to accomplish the task.
1
You may consider a simplerfor(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.
– Holger
Jan 11 at 8:05
add a comment |
There are different ways to create a sorted array of int
s out of an unsorted one using streams, as the other answers show. These approaches have the disadvantage of either requiring boxing/unboxing (so that a Comparator<Integer>
can be used), or that new arrays are needed to accommodate the elements.
Here's a way to sort in-place without boxing/unboxing. First, in ascending order:
int arr2 = ...
Arrays.sort(arr2);
Unfortunately, there's no way to sort in-place in descending order using a single-line operation. You will need to sort ascending first, then reverse the array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
for (int left = 0; left < size / 2; left++) {
int right = size - i - 1;
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
EDIT: As @Holger points out in the comments, the for
loop above could be improved as follows:
for (int left = 0, right = arr2.length - 1; left < right; left++, right--) {
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
An alternative is to sort in ascending order and then place the elements in reverse order into a new array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
int reversed = new int[size];
Arrays.setAll(reversed, i -> arr2[size - i - 1]);
This uses Arrays.setAll
to accomplish the task.
1
You may consider a simplerfor(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.
– Holger
Jan 11 at 8:05
add a comment |
There are different ways to create a sorted array of int
s out of an unsorted one using streams, as the other answers show. These approaches have the disadvantage of either requiring boxing/unboxing (so that a Comparator<Integer>
can be used), or that new arrays are needed to accommodate the elements.
Here's a way to sort in-place without boxing/unboxing. First, in ascending order:
int arr2 = ...
Arrays.sort(arr2);
Unfortunately, there's no way to sort in-place in descending order using a single-line operation. You will need to sort ascending first, then reverse the array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
for (int left = 0; left < size / 2; left++) {
int right = size - i - 1;
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
EDIT: As @Holger points out in the comments, the for
loop above could be improved as follows:
for (int left = 0, right = arr2.length - 1; left < right; left++, right--) {
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
An alternative is to sort in ascending order and then place the elements in reverse order into a new array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
int reversed = new int[size];
Arrays.setAll(reversed, i -> arr2[size - i - 1]);
This uses Arrays.setAll
to accomplish the task.
There are different ways to create a sorted array of int
s out of an unsorted one using streams, as the other answers show. These approaches have the disadvantage of either requiring boxing/unboxing (so that a Comparator<Integer>
can be used), or that new arrays are needed to accommodate the elements.
Here's a way to sort in-place without boxing/unboxing. First, in ascending order:
int arr2 = ...
Arrays.sort(arr2);
Unfortunately, there's no way to sort in-place in descending order using a single-line operation. You will need to sort ascending first, then reverse the array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
for (int left = 0; left < size / 2; left++) {
int right = size - i - 1;
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
EDIT: As @Holger points out in the comments, the for
loop above could be improved as follows:
for (int left = 0, right = arr2.length - 1; left < right; left++, right--) {
int temp = arr2[right];
arr2[right] = arr2[left];
arr2[left] = temp;
}
An alternative is to sort in ascending order and then place the elements in reverse order into a new array:
int arr2 = ...
Arrays.sort(arr2);
int size = arr2.length;
int reversed = new int[size];
Arrays.setAll(reversed, i -> arr2[size - i - 1]);
This uses Arrays.setAll
to accomplish the task.
edited Jan 11 at 13:51
answered Jan 10 at 18:22
Federico Peralta SchaffnerFederico Peralta Schaffner
23.8k43780
23.8k43780
1
You may consider a simplerfor(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.
– Holger
Jan 11 at 8:05
add a comment |
1
You may consider a simplerfor(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.
– Holger
Jan 11 at 8:05
1
1
You may consider a simpler
for(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.– Holger
Jan 11 at 8:05
You may consider a simpler
for(int left = 0, right = arr2.length-1; left < right; left++, right--) …
which may also be more efficient in some cases.– Holger
Jan 11 at 8:05
add a comment |
If you explicitly need a custom comparator lambda, try this one:
int arr2 = new int {54,432,53,21,43};
int arr3 = IntStream.of(arr2).boxed().sorted((a, b) -> a - b).mapToInt(Integer::intValue).toArray();
add a comment |
If you explicitly need a custom comparator lambda, try this one:
int arr2 = new int {54,432,53,21,43};
int arr3 = IntStream.of(arr2).boxed().sorted((a, b) -> a - b).mapToInt(Integer::intValue).toArray();
add a comment |
If you explicitly need a custom comparator lambda, try this one:
int arr2 = new int {54,432,53,21,43};
int arr3 = IntStream.of(arr2).boxed().sorted((a, b) -> a - b).mapToInt(Integer::intValue).toArray();
If you explicitly need a custom comparator lambda, try this one:
int arr2 = new int {54,432,53,21,43};
int arr3 = IntStream.of(arr2).boxed().sorted((a, b) -> a - b).mapToInt(Integer::intValue).toArray();
answered Jan 10 at 11:06
SunchezzSunchezz
4615
4615
add a comment |
add a comment |
public class lambdaTest {
public static void main(String args) {
int arr2 = new int {54,432,53,21,43};
int sorted = IntStream.of(arr2)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
System.out.println("In decending Order:");
for(int ss : sorted)
{
System.out.print(ss+", ");
}
System.out.println();
int reversed = IntStream.range(0, sorted.length)
.map(i -> sorted[sorted.length-i-1])
.toArray();
System.out.println("In Ascending Order: ");
for(int ss1 : reversed)
{
System.out.print(ss1+", ");
}
}
}
OUTPUT
In decending Order:
432, 54, 53, 43, 21,
In Ascending Order:
21, 43, 53, 54, 432,
Edit: much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray())
Thanks to Holger
1
It would be much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.
– Holger
Jan 10 at 11:23
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
1
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using aComparator
).
– Holger
Jan 10 at 11:27
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
add a comment |
public class lambdaTest {
public static void main(String args) {
int arr2 = new int {54,432,53,21,43};
int sorted = IntStream.of(arr2)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
System.out.println("In decending Order:");
for(int ss : sorted)
{
System.out.print(ss+", ");
}
System.out.println();
int reversed = IntStream.range(0, sorted.length)
.map(i -> sorted[sorted.length-i-1])
.toArray();
System.out.println("In Ascending Order: ");
for(int ss1 : reversed)
{
System.out.print(ss1+", ");
}
}
}
OUTPUT
In decending Order:
432, 54, 53, 43, 21,
In Ascending Order:
21, 43, 53, 54, 432,
Edit: much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray())
Thanks to Holger
1
It would be much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.
– Holger
Jan 10 at 11:23
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
1
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using aComparator
).
– Holger
Jan 10 at 11:27
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
add a comment |
public class lambdaTest {
public static void main(String args) {
int arr2 = new int {54,432,53,21,43};
int sorted = IntStream.of(arr2)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
System.out.println("In decending Order:");
for(int ss : sorted)
{
System.out.print(ss+", ");
}
System.out.println();
int reversed = IntStream.range(0, sorted.length)
.map(i -> sorted[sorted.length-i-1])
.toArray();
System.out.println("In Ascending Order: ");
for(int ss1 : reversed)
{
System.out.print(ss1+", ");
}
}
}
OUTPUT
In decending Order:
432, 54, 53, 43, 21,
In Ascending Order:
21, 43, 53, 54, 432,
Edit: much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray())
Thanks to Holger
public class lambdaTest {
public static void main(String args) {
int arr2 = new int {54,432,53,21,43};
int sorted = IntStream.of(arr2)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
System.out.println("In decending Order:");
for(int ss : sorted)
{
System.out.print(ss+", ");
}
System.out.println();
int reversed = IntStream.range(0, sorted.length)
.map(i -> sorted[sorted.length-i-1])
.toArray();
System.out.println("In Ascending Order: ");
for(int ss1 : reversed)
{
System.out.print(ss1+", ");
}
}
}
OUTPUT
In decending Order:
432, 54, 53, 43, 21,
In Ascending Order:
21, 43, 53, 54, 432,
Edit: much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray())
Thanks to Holger
edited Jan 10 at 11:50
answered Jan 10 at 11:00
Common ManCommon Man
2,24131431
2,24131431
1
It would be much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.
– Holger
Jan 10 at 11:23
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
1
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using aComparator
).
– Holger
Jan 10 at 11:27
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
add a comment |
1
It would be much simpler to sort in natural order (IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.
– Holger
Jan 10 at 11:23
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
1
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using aComparator
).
– Holger
Jan 10 at 11:27
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
1
1
It would be much simpler to sort in natural order (
IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.– Holger
Jan 10 at 11:23
It would be much simpler to sort in natural order (
IntStream.of(arr2) .sorted() .toArray()
) and reverse that, to get both, instead of sorting in reverse order and reverse that again.– Holger
Jan 10 at 11:23
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
Yeah, i got it, but i presented other way of doing it :?, hope it is ok??
– Common Man
Jan 10 at 11:25
1
1
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using a
Comparator
).– Holger
Jan 10 at 11:27
Sure, but there’s an advantage in the approach of reversing the array, as together with a straight-forward ascending order sort, you can do it without any boxing overhead. That advantage gets lost when doing the first sort with boxed values (as unavoidable when using a
Comparator
).– Holger
Jan 10 at 11:27
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
@Holger , thank you sir , i learnt it from you now :)
– Common Man
Jan 10 at 11:28
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.
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%2f54126952%2fhow-to-sort-integer-array-in-ascending-and-descending-order-using-lambda-only-in%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
7
Never use a comparator like
(a,b)->a-b
forint
values. It may work in some use cases, but the difference between twoint
values may be bigger than theint
value range and cause overflows. Therefore, use(a,b) -> Integer.compare(a, b)
resp.Integer::compare
. To reverse the order, use(a,b) -> Integer.compare(b, a)
. Do not negate the value returned by a compare function, that will fail if the value isInteger.MIN_VALUE
.– Holger
Jan 10 at 11:15
4
"giving error" what error? Please specify this information.
– Ian Kemp
Jan 10 at 11:25
2
@IanKemp in this case, it’s obvious enough. Arrays don’t have a
sort
method and thesort(T a, Comparator<? super T> c)
method does not support primitive type arrays.– Holger
Jan 10 at 11:30
3
@Holger Whether it's obvious enough is irrelevant - the rules specify that a question must include a specific problem or error. "Giving error" is the same as saying "doesn't work", which is not helpful to anyone - especially not people who might be looking for the specific error caused by using a comparator like
(a,b)->a-b
withInteger.MIN_VALUE
.– Ian Kemp
Jan 10 at 11:59
2
@Holger Thank you for continuing the battle to eradicate subtraction as a means to compare two int values.
– Stuart Marks
Jan 10 at 18:52