1

I already know how to sort an ArrayList but I wanna know if this is possible to sort an Array with two arguments like: I have an array 5 same objects with a float and a String in it like that:

- object 1 : 0 "DD"
- object 2 : 3 "FF"
- object 3 : 1 "GG"
- object 4 : 2 "AA"
- object 5 : 1 "AA"

And I want sort them like that:

- object 1 : 0 "DD"
- object 5 : 1 "AA"
- object 3 : 1 "GG"
- object 4 : 2 "AA"
- object 2 : 3 "FF"

Is it possible to sort them with a comparator by multiplying the Float.compare() and the String.compare() ? or do you need to sort them first with the Float.compare() and then create sub-arrays to compare with the String.compare() ?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
FuxTheFox
  • 99
  • 1
  • 9
  • 1
    A mixture of `regex` and `sorting` will suffice.Use `:` as the separator in `String.split()` and then sort those arrays using `Arrays.sort()`!!! – Am_I_Helpful Oct 29 '14 at 07:20
  • possible duplicate of [Java sort problem by two fields](http://stackoverflow.com/questions/4805606/java-sort-problem-by-two-fields) – cheseaux Oct 29 '14 at 07:21

2 Answers2

3

Yes, of course. You just need a comparator that compares elements by their float value and, if their float value are equal, compares them by their string value:

public class FooComparator implements Comparator<Foo> {
    @Override
    public int compare(Foo f1, Foo f2) {
        int result = Float.compare(f1.getFloatValue(), f2.getFloatValue());
        if (result == 0) {
            result = f1.getStringValue().compareTo(f2.getStringValue());
        }
        return result;
    }
}

Java 8 can even do that for you:

Comparator<Foo> c = Comparator.comparingDouble(Foo::getFloatValue)
                              .thenComparing(Foo::getStringValue);
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • +1 From Acache Commons I founded useful `ChainComparator` https://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/org/apache/commons/collections/comparators/ComparatorChain.html – Ezequiel Oct 29 '14 at 07:28
2

You need to define your class as Comparable:

public MyClass implements Comparable<MyClass> {
    private float f;
    private String s;

    @Override
    public int compare (MyClass other) {
       int first = Float.compare(f, other.f);
       if (first != 0) {
           return first;
       }

       return s.compare(other.s);
    }
}

And then just call Arrays.sort(myList).

Mureinik
  • 297,002
  • 52
  • 306
  • 350