Android - Is it possible to sort lists using Comparator.comparing instead of custom Comparators on APIs < 24?

VerumCH :

I have a RecyclerView in the app I'm working on that I can populate with various items and search/filter/sort/so on. Currently working on sorting.

I have multiple criteria that I can sort by, which can be selected from a drop-down spinner. The values being sorted on in the data objects include Strings, ints, and enums, all of which are fairly easy to sort. However, while some of the sorting options only need one criteria, some require secondary or tertiary criteria (and in some very rare cases up to 4). That's quite a ton of custom Comparators I would have to write in order to effectively use Collections.sort(List, Comparator), so I was hoping there might be some way to avoid that.

Turns out, Java 8 has a great solution: Comparator.comparing(...), which generates Comparators for you and can be easily extended indefinitely via Comparator.comparing().thenComparing().thenComparing().... It also has List myList.sort(), which I'm not sure of the efficiency compared to Collections.sort(myList), but it feels cleaner to me. And I looked into it, and thought just my luck! Android has been supporting many Java 8 features for a while now!

Unfortunately, Android Studio tells me that, for some reason, Comparator.comparing() as well as List::sort are only supported on API 24 and above. That won't realistically work for me, since the app I'm working on "needs to" run as low as API 15-16. I find this odd, however, since the other Java 8 features I've tried (lambda expressions like (o1, o2) -> (o1.toString().compareTo(o2.toString()) and method references like List::sort above) work fine on all API levels in the range I've checked as long as you specify targeting Java 8. And it is a Java 8 thing after all, not an Android thing.

So with all that in mind, is there a way to make Comparator.comparing() and List::sort work below API 24? I haven't found anything in my Google searches, they all end up just pointing to Android's Java 8 "documentation" or the JavaDocs for Comparator and List. Either something in one of Android's support libraries (seems unlikely) or a third-party library/hack like Retrolambda?

Anton Malyshev :

Try streamsupport library porting some of java 8 features to java 6/7: https://github.com/streamsupport

They have the class you need: https://github.com/streamsupport/streamsupport/blob/master/src/main/java/java8/util/Comparators.java (it was renamed from Comparator to Comparators only to avoid name conflicts).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=435878&siteId=1
Recommended