Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Integer list as if it were a String list in Java

Tags:

java

list

sorting

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 that requires to make a new String array and convert them individually and sort it and convert it back to Integer and reassign it. Also, a Comparator I presume wouldn't be much different.

So are there more ways to do this?

like image 295
Megid Avatar asked Feb 03 '26 16:02

Megid


1 Answers

The two straight forward choices are:

  • creating a List<String> from your List<Integer>, to then sort that String list, and turn it back into an Integer list in the end.
  • using a custom comparator

The major difference: when you create list of strings initially, then you have to do that transformation Integer -> String ... exactly once per input number.

When you do that within the comparator, then you are doing it probably much more often! As you will be using a Comparator<Integer, Integer> ... which will always need to turn both arguments into Strings. Or do the relatively expensive math to determine the "length" of the input numbers.

Beyond that: unless we are talking about code that works on millions of numbers; or that is called a thousands of time each minute ... worrying about performance is simply wrong. Worry 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 other solution: you could use some Pair<String, Integer> class; with the String generated from the Integer number. Now you put those into a List, and use a comparator to sort on the String part of the Pair. Then you don't need another conversion; you simply walk the pairs, and you fetch the Integer numbers from each pair. But again, that is micro-performance-management and is "for the fun" only.

like image 166
GhostCat Avatar answered Feb 05 '26 05:02

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!