How can I write: (javascript)
array.sort((a, b) => a - b)
To Java? -- I've already tried:
Arrays.sort(array, (a, b) -> a - b);
but I get an error says no suitable method found.
How can I write: (javascript)
array.sort((a, b) => a - b)
To Java? -- I've already tried:
Arrays.sort(array, (a, b) -> a - b);
but I get an error says no suitable method found.
Not very good with javascript, yet searching for how javascript sorts elements, your code
array.sort((a, b) => a - b)
seems to be sorting an array in an ascending order, at the same time coincidently looking at another question from you, the code equivalent for that kind of sorting in java would be
public static int[] smallestToLargestArrangement(int[] arr) {
Arrays.sort(arr); // sorts ascendingly
return arr;
}
Note:- I tried relating the context of your trials to come up with that method, the general approach would be to inline the sort
call as and when required.
Well After a couple days and about 12 hours of working I managed to figure it out on my own... Thanks ;-)
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
public class Solution {
public static int largestArrangement(int[] arr) {
return Integer.parseInt(StringUtils.join(Arrays.stream(arr).boxed().sorted((a, b) -> Integer.parseInt(""+b+a) - Integer.parseInt(""+a+b)).mapToInt(i -> i).mapToObj(String::valueOf).toArray(String[]::new), ""));
}
}