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() ?

2
  • 1
    A mixture of regex and sorting will suffice.Use : as the separator in String.split() and then sort those arrays using Arrays.sort()!!! Commented Oct 29, 2014 at 7:20
  • possible duplicate of Java sort problem by two fields Commented Oct 29, 2014 at 7:21

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 From Acache Commons I founded useful ChainComparator commons.apache.org/proper/commons-collections/javadocs/…
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.