0

This question is asking another method for sorting other than using Collections.reverse().

I wanted to sort a list in ascending and descending also. I want to do that without using override methods. I have tried Collections.reverse().It worked fine. But I want to find another method. Anyone can help me with that?

 Collections.sort(list, (Comparator.<ModelPortfolioDTO>
                        comparingDouble(mp1 -> Double.parseDouble(mp1.getSharpRatio()))
                        .thenComparingDouble(mp2 -> Double.parseDouble(mp2.getSharpRatio()))));
R0b1n
  • 513
  • 1
  • 5
  • 28
  • 3
    Does this answer your question? [Reverse a comparator in Java 8](https://stackoverflow.com/questions/32995559/reverse-a-comparator-in-java-8) – Amongalen Jun 22 '20 at 12:52
  • 1
    This question is not a duplicate, the OP asked for another method apart from `reverse`. – Arcanefoam Jun 22 '20 at 13:55

1 Answers1

1

The collections.sort method accepts a comparator, which has a sort method. The javadoc of that method provides the answer:

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

So by changing the value returned, you can change the order. You can code your own or use the primitive type implementations (since you are sorting via double values). Ascending:

 @Override
    public int compare(ModelPortfolioDTO o1, ModelPortfolioDTO o2) {
        return Double.compare(Double.parseDouble(o1.getSharpRatio()), Double.parseDouble(o2.getSharpRatio()));
    }

Descending (notice the inverted order of elements):

 @Override
public int compare(ModelPortfolioDTO o1, ModelPortfolioDTO o2) {
    return Double.compare(Double.parseDouble(o2.getSharpRatio()), Double.parseDouble(o1.getSharpRatio()));
}
Arcanefoam
  • 687
  • 7
  • 20