【问题标题】:sort arraylist using startwith for api < 24使用 startwith 对 api < 24 的数组列表进行排序
【发布时间】:2021-02-14 13:47:51
【问题描述】:

我创建了一个 autocompleteTextView,它显示了我从客户端获得的结果,该结果取决于用户输入的查询。

来自客户端的结果没有以任何方式排序。

例如,如果用户输入 harry pot 我可以得到:

harry and the tree
the trees and harry
harry pot right
ben and harry
harry and be

等等。

我希望结果会按相关性显示 = 如果用户输入 harry pot 我想假设它以 harry pot 开头。

harry pot right
harry and be
harry and the tree
the trees and harry
ben and harry

如何对我的 ArrayList 进行排序以首先显示以该查询开头的结果?

我尝试使用 streamcomperator,但两者都需要 API >= 24。

对于较低的 API 有什么办法吗? (具体需要 API = 21)。

谢谢

【问题讨论】:

    标签: java android java-stream comparator


    【解决方案1】:

    List 调用Collections.sort(list, comparator) 进行排序(API 级别1)

    【讨论】:

    • 我找不到关于比较器和startsWith以及如何实现它的任何内容。
    • @Ben 由于没有一个结果以"harry pot" 开头,所以没有什么要排序的。
    【解决方案2】:

    试试

    Collections.sort(arrayList, new Comparator<Element>() {
        @Override
        public int compare(Element element, Element t1) {
            if(element.time > t1.time) return -1;
            else return 1;
        }
    });
    

    它适用于 API 23

    【讨论】:

    • 您也许可以使用 lambda 来缩短它((element, t1) -&gt; t1.time - element.time 或类似的东西)。不知道你从哪里得到Element 和时间,不过,问题似乎不包括那个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    相关资源
    最近更新 更多