Sorting Integer list as if it were a list of strings in Java
I have a simple array of integers and I want to sort them, but by String rules
Example: {1, 7, 43, 15, 2, 12} -> {1, 12, 15, 2, 43, 7}
I looked around and found Integer.toString(int)
and String.valueOf(int)
, but this requires creating a new String array and converting them individually and sorting it and converting to Integer and reassigning. Also, I suppose the comparator comparator won't be much different.
So, are there any ways to do this?
source to share
Two direct choices:
- create
List<String>
from yoursList<Integer>
to then sort the String list and return it back to the Integer list at the end. - using a tunable comparator
Difference major : when creating a list of strings, initially you have to do this conversion Integer -> String ... exactly once for each input number.
When you do this in a comparator, you probably do it much more often! Since you will be using Comparator<Integer, Integer>
... that will always have to turn both arguments to strings. Or do some relatively expensive math to determine the "length" of the input numbers.
In addition: if we are not talking about code that works with millions of numbers; or it's called thousands of times a minute ... it's just wrong to worry about performance. Concern about the readability of your code and the effort required to maintain it in the future.
Finally: if you see this as a challenge, how to solve this problem using "interesting" ways; one more solution: you can use some class Pair<String, Integer>
; with a string generated from Integer. Now you put them in a list and use a comparator to sort by the String part of the pair. Then you don't need another conversion; you just loop through the pairs and you get Integer numbers from each pair. But again, this is micro-efficiency management and only "for fun".
source to share
Here's an example using a custom integer- Comparator
based representation String
:
Integer[] intArray = { 1, 7, 43, 15, 2, 12 };
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(final Integer o1, final Integer o2) {
return String.valueOf(o1).compareTo(String.valueOf(o2));
}
};
Arrays.sort(intArray, comparator);
System.out.println(Arrays.toString(intArray));
source to share
You can use custom Comparator
. You can keep it generic if you w ant to use it for other types:
class StringComparator<T> implements Comparator<T> {
@Override
public int compare(T first, T second) {
// compare String representations
return first.toString().compareTo(second.toString());
}
}
Then you can sort:
Integer[] a = {1; 2; 3; 11; 22}
Arrays.sort(a, new StringComparator<Integer>());
source to share