0

I have an array list that is set up in this type of style...

  • 4 dogs
  • 10 cats
  • 2 dogs

And I want to sort it so the ArrayList will be in the order of...

  • 1 dogs
  • 4 dogs
  • 10 cats

Without using a comparator or another method, what is the shortest, easiest way to sort these by taking out the numbers (splitting the string by the space " "?), comparing them, and putting the sorted results back into the ArrayList? If you could attach your code snippet, it would be much appreciated.

Zack
  • 5,108
  • 4
  • 27
  • 39
  • 2
    possible duplicate of [Sorting an Arraylist that contains strings with numbers](http://stackoverflow.com/questions/22669270/sorting-an-arraylist-that-contains-strings-with-numbers) – assylias Mar 27 '14 at 12:56
  • 3
    Makes no sense to me that you don't want to use a Comparator. Someone has to compare the items, no? How else would you deduce which item is bigger. – darijan Mar 27 '14 at 12:56
  • comparator is best way of sorting. Use it. – Deepu--Java Mar 27 '14 at 12:57
  • Sorry, I misunderstood the definition of comparator. This is exactly what I meant. Thank you! – Zack Mar 27 '14 at 13:13

3 Answers3

5

The simplest way is to use comparator:

Collections.sort(list, new Comparator<String>() {
    public void compare(String one, String two) {
         return getNumber(one) - getNumber(two);
    }
    private int getNumber(String str) {
        return Integer.parseInt(one.split(" ")[0]);
    }
}

I really do not know what can be simpler.

AlexR
  • 114,158
  • 16
  • 130
  • 208
2

Without an explicit Comparator, try using Java 8's Lambda feature:

//Assuming that the list variable is a string that looks like e.g. "1 10 2 5"

Arrays.sort(list.split(" "), 
    (String a, String b) -> { return Integer.valueOf(a).compareTo(Integer.valueOf(b)) }; 
);

//Assuming that the list variable is an array list of Strings

Collections.sort(list, 
    (String a, String b) -> { return Integer.valueOf(a).compareTo(Integer.valueOf(b)) }; 
);
darijan
  • 9,725
  • 25
  • 38
1

You need to create a class have String field in that class and implement compareTo method and write comparison logic.

Use this class object in ArrayList and then use Collections.sort method.

codingenious
  • 8,385
  • 12
  • 60
  • 90