【问题标题】:Sort an arraylist using multiple conditions comparing item’s field with an external field使用多个条件对数组列表进行排序,将项目的字段与外部字段进行比较
【发布时间】:2019-11-07 05:53:28
【问题描述】:

我想按以下顺序对数组列表进行排序-

1.在顶部显示代码与搜索文本完全匹配的项目。

2.下方显示名称与搜索文本完全匹配的项目。

3.下方显示以搜索文本开头的代码项。

4.下面显示名称以搜索文本开头的项目。

  1. 下面显示名称包含搜索文本的项目。

我为此使用了以下代码-

xyzArrayList.sortWith(compareBy<XYZ>{it.code==searchedText}.thenBy{it.name==searchedText}.thenBy {it.code?.startsWith(searchedText)}.thenBy{it.name?.startsWith(searchedText)}.thenBy { it.name?.contains(searchedText) })

但上面的代码并没有对列表进行排序。我哪里出错了,如何实现我的要求?

【问题讨论】:

    标签: android sorting arraylist kotlin


    【解决方案1】:

    也许,您可以利用Collections 上的另一个扩展功能partition,而不是使用sortWiththenBy

    这个函数接受一个谓词并创建一个Pair&lt;List&lt;T&gt;, List&lt;T&gt;&gt;,其中第一个列表包含与谓词匹配的元素,第二个列表包含所有其他元素。

    我们来看一个例子:

    val cities = ["Berlin", "London", "Paris", "Rome", "Budapest", "Barcelona"]
    
    // Here we apply a predicate to create the first partition
    val searchQuery = "B"
    val (matchingElements, nonMatchingElements) 
         = cities.partition { it == searchQuery } //([], ["Berlin", "London", "Paris", "Rome", "Budapest", "Barcelona"]
    
    // Now potentially we could create another partition from the nonMatchingElements list
    val (startingWithQuery, others) = nonMatchingElements
        .partition { it.startsWith(searchQuery) }
    
    println(matchingElements) // []
    println(startingWithQuery) // ["Berlin", "Budapest", "Barcelona"]
    println(others) // ["London", "Paris", "Rome"]
    

    创建所需的所有分区后,您现在可以按正确顺序从所需的所有分区中生成一个列表,或者用一些分隔符显示这些不同的列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-18
      • 2022-10-13
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多