java comparator, how to sort by integer?

后端 未结 6 1014
一整个雨季
一整个雨季 2020-12-08 09:36

Im trying to learn comparator in java and I have found this great example online, my question is how would this code be changed so that the pet names are ordered by age and

6条回答
  •  忘掉有多难
    2020-12-08 10:16

    If you have access to the Java 8 Comparable API, Comparable.comparingToInt() may be of use. (See Java 8 Comparable Documentation).

    For example, a Comparator to sort Dog instances descending by age could be created with the following:

    Comparable.comparingToInt(Dog::getDogAge).reversed();

    The function take a lambda mapping T to Integer, and creates an ascending comparator. The chained function .reversed() turns the ascending comparator into a descending comparator.

    Note: while this may not be useful for most versions of Android out there, I came across this question while searching for similar information for a non-Android Java application. I thought it might be useful to others in the same spot to see what I ended up settling on.

提交回复
热议问题