Kotlin-数组列表-如果少于两个,如何删除T类型的所有元素

Kotlin-数组列表-如果少于两个,如何删除T类型的所有元素,kotlin,collections,Kotlin,Collections,我在kotlin中有一个可变列表,如下所示: [Section(title=fruit), Food(name=orange), Food(name=banana), Food(name=apple), Section(title=vegetable), Food(name=potato), Food(name=cucumber), Food(name=salad)] val食品杂货=清单 食物、水果、, 食物、蔬菜、, 食品、水果、, 食物、水果、, 食用黄瓜、蔬菜、, 食品、蔬菜 我已

我在kotlin中有一个可变列表,如下所示:

[Section(title=fruit), Food(name=orange), Food(name=banana), Food(name=apple),  Section(title=vegetable), Food(name=potato), Food(name=cucumber), Food(name=salad)]
val食品杂货=清单 食物、水果、, 食物、蔬菜、, 食品、水果、, 食物、水果、, 食用黄瓜、蔬菜、, 食品、蔬菜

我已经定义了一个密封类,以便可以对这些数据进行分组:

sealed class RecyclerItem {
    data class Food(val name: String): RecyclerItem()
    data class Section(val title: String): RecyclerItem()
}
哪一部分是蔬菜或水果 食物会像香蕉或苹果 等等

为了将数据分组到单个列表中,我使用groupby编写了以下代码:

val sectionedGroceries: List<RecyclerItem> = groceries
            .groupBy { it.category }
            .flatMap { (category, foods) ->
                listOf<RecyclerItem>(RecyclerItem.Section(category)) + foods.map { RecyclerItem.Food(it.name) }
            }
但现在我的问题是,如果列表中只有一个部分,我想删除它,这样列表中就只有食物了。我如何才能最有效地做到这一点

更新抱歉,以下是完整代码:

    class MainActivity : FragmentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val groceries = listOf(
            Food("orange", "fruit"),
            Food("potato", "vegetable"),
            Food("banana", "fruit"),
            Food("apple", "fruit"),
            Food("cucumber", "vegetable"),
            Food("salad", "vegetable")
        )

            val sectionedGroceries: List<RecyclerItem> = groceries
                .groupBy { it.category }
                .flatMap { (category, foods) ->
                    listOf<RecyclerItem>(RecyclerItem.Section(category)) + foods }

        Log.v("TAG","$sectionedGroceries")
    }
}


sealed class RecyclerItem {
    data class Food(val name: String, val category: String): RecyclerItem()
    data class Section(val title: String): RecyclerItem()
}

食物在密封类中只有一个参数,但在杂货列表中有两个参数。类别定义在哪里?我更新了代码,现在非常清楚了。我粘贴了完整的代码。如果只有一个小节,我只想从最终结果中删除所有小节数据类,因为一个小节对我的用例毫无意义。let语句是我的问题,我一直认为它是一个rxjava流,而它不是。它的kotlin功能。。谢谢
val sectionedGroceries: List<RecyclerItem> = groceries
    .groupBy { it.category }
    .let {
        if (it.size == 1) it.values.first()
        else it.flatMap { (category, foods) ->
            listOf(RecyclerItem.Section(category)) + foods
        }
    }