1

I have a list with value 994 days, 973 days, 1094 days, 1092 days, 189 days, 184 days and want to perform sort in ascending order. So when use Collections.sort() its sorting in incorrect order

  List<String>  list = new LinkedList<String>();
   list.add("994 days");
   list.add("973 days");
   list.add("1094 days");
   list.add("1092 days");
   list.add("189 days");
   list.add("184 days");

i want to sort this in ascending order so my output has to be : 184 days, 189 days, 973 days, 994 days,1092 days, 1094 days

MVLS
  • 37
  • 3
  • if the pattern is going to be `"N days"` for every item, you can isolate the number (for example through regular expression = `^(\d+) days$`, group 1) and sort by that. – sephiroth Nov 14 '19 at 10:34
  • simply remove days and trim your String and then convert it to Integer sort and you will get your desired result. and again convert these value to sting array list – Atif AbbAsi Nov 14 '19 at 10:46
  • Possible duplicate of [Sort on a string that may contain a number](https://stackoverflow.com/q/104599/5221149) – Andreas Nov 14 '19 at 10:47

2 Answers2

5

You can use Comparator.comparingInt which required a function to extract an int from your object, in this case a String:

list.sort(Comparator.comparingInt(s -> Integer.valueOf(s.split(" ")[0])));

Integer.valueOf(s.split(" ")[0]) will keep only the number from your string:

"198 days" -> 198

Jorj
  • 1,291
  • 1
  • 11
  • 32
-1

Add a comparator which extract integer part and returns the result accordingly. Something like this.

class DatesCompare implements Comparator<String> 
{ 
    public int compare(String d1, String d2) 
    { 
        int d1num = Integer.parseInt(d1.split(" ")[0]);
        int d2num = Integer.parseInt(d2.split(" ")[0]);
        if (d1num < d2num) return -1; 
        if (d1num > d2num ) return 1; 
        else return 0; 
    } 
} 

Collections.sort(list, new DatesCompare())
skott
  • 554
  • 3
  • 9