Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用多个条件对arraylist排序,比较项的字段和外部字段_Android_Sorting_Arraylist_Kotlin - Fatal编程技术网

Android 使用多个条件对arraylist排序,比较项的字段和外部字段

Android 使用多个条件对arraylist排序,比较项的字段和外部字段,android,sorting,arraylist,kotlin,Android,Sorting,Arraylist,Kotlin,我想按以下顺序对arraylist进行排序- 1.顶部显示代码与搜索文本完全匹配的项目 2.下面显示名称与搜索文本完全匹配的项目 3.下面显示代码以搜索文本开头的项目 4.下面显示名称以搜索文本开头的项目 下面显示名称中包含搜索文本的项目。 我使用了下面的代码- xyzArrayList.sortWith(compareBy<XYZ>{it.code==searchedText}.thenBy{it.name==searchedText}.thenBy {it.code?.start

我想按以下顺序对arraylist进行排序-

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

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

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

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

下面显示名称中包含搜索文本的项目。 我使用了下面的代码-

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) })
但是上面的代码没有对列表进行排序。我哪里出了问题?我如何才能达到我的要求?

也许,您可以利用集合上另一个名为partition的扩展函数,而不是使用sortWith和thenBy

此函数接受谓词并创建一对,其中第一个列表包含与谓词匹配的元素,第二个列表包含所有其他元素

让我们看一个例子:

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"]
在创建了所有需要的分区之后,现在可以按正确的顺序从所有需要的分区生成一个列表,或者用一些分隔符显示这些不同的列表