如何对 RecyclerView 中的项目进行排序?

我想对 recyclerView 中的项目进行排序。我有诸如 20ABC1、20ABC2、...、20ABC10、..等的用户名。

我已经尝试了相关问题的答案,其中之一是:

public static final Comparator<Users> BY_NAME_ALPHABETICAL = (users, t1) -> users.Username.compareTo(t1.Username);

但这并不能完全解决问题。20ABC10, 20ABC11,...20ABC19 高于 20ABC2。我认为这是因为它逐个字符地检查。

有什么办法可以解决这个问题?

谢谢 :)


函数式编程
浏览 159回答 4
4回答

炎炎设计

我的问题通过使用这个答案解决了我的问题Sorting Strings that contains number in Java&nbsp;by Bohemian 他从字符串中删除了字母并比较了剩余的intsCollections.sort(strings, new Comparator<String>() {&nbsp; &nbsp; public int compare(String o1, String o2) {&nbsp; &nbsp; &nbsp; &nbsp; return extractInt(o1) - extractInt(o2);&nbsp; &nbsp; }&nbsp; &nbsp; int extractInt(String s) {&nbsp; &nbsp; &nbsp; &nbsp; String num = s.replaceAll("\\D", "");&nbsp; &nbsp; &nbsp; &nbsp; // return 0 if no digits found&nbsp; &nbsp; &nbsp; &nbsp; return num.isEmpty() ? 0 : Integer.parseInt(num);&nbsp; &nbsp; }});

撒科打诨

public Observable<User> getUsersWithBlogs() {return Observable.fromIterable(UserCache.getAllUsers()).filter(user -> user.blog != null && !user.blog.isEmpty()).sorted((user1, user2) -> user1.name.compareTo(user2.name));}

芜湖不芜

使用科特林,val comp: Comparator<Users> = Comparator { o1, o2 -> o1.Username.trim().compareTo(o2.Username.trim()) }Collections.sort(users, comp)对 java 做同样的事情。

ABOUTYOU

把它放在你的适配器里void sortByName(boolean isDescending) {&nbsp; &nbsp; if (mDataList.size() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; Collections.sort(mDataList, new Comparator<Users>() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public int compare(Users object1, Users object2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (isDescending)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return object2.getUsername().toLowerCase().compareTo(object1.getUsername().toLowerCase().trim());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return object1.getUsername().toLowerCase().compareTo(object2.getUsername().toLowerCase().trim());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; notifyDataSetChanged();&nbsp; &nbsp; }}然后像这样使用它:adapter.sortByName( true||false );
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java