• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need Help - Sorting an ArrayList of Strings

 
K Bala
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an ArrayList of Strings like this

"132 8"
"132 12"
"132 4"
"132 19"

When I sort it using Collections.sort() method, I get

132 12
132 19
132 4
132 8

I want the ArrayList to be sorted like this

132 4
132 8
132 12
132 19

How can I achieve this? Please help
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'll need a custom comparator that, when comparing, splits the strings based on the space (hint: String.split), then converts the array elements to Integers (or Longs, depending on the length), and then compares these.

As for the comparing of the Integers, you'll need to compare the separate parts. Something like this:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic