我有一段代码:

/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */

class Person(val firstName: String, val lastName: String, var age: Int, var isEmployed: Boolean, var companyName: String)
{
    override fun toString(): String = firstName + " " + lastName + ", age:" + 
    age + ", isEmployed: " + isEmployed + ", companyName:" + companyName + "\n"
}


fun main() {
    
    var alist = emptyList<Person>()
    alist += (Person("Alan", "Walker", 23, true, "Google"))
    alist += (Person("Bee", "dog", 24, true, "Google"))
    alist += (Person("John", "Cena", 25, true, "Google"))
    alist += (Person("See", "S", 26, true, "Stackoverflow"))
    alist += (Person("Soya", "A", 27, true, "Stackoverflow"))
    alist += (Person("Zander", "Cage", 28, true, "Stackoverflow"))
    
    
    println(alist)
    
    var uniqueGoogle = alist.filter{ it.companyName.equals("Google") }.first()
    var newList = alist.filter{ !it.companyName.equals("Google") }
    newList = uniqueGoogle + newList
    
    println(newList)
}

我需要从上面的名单上的人的名单是唯一的公司名称只为谷歌.我真的不擅长使用列表聚合,这里需要一些帮助.

println(newList)的预期输出:

[Alan Walker, age:23, isEmployed: true, companyName:Google
, See S, age:23, isEmployed: true, companyName:Stackoverflow
, Soya A, age:23, isEmployed: true, companyName:Stackoverflow
, Zander Cage, age:23, isEmployed: true, companyName:Stackoverflow
]

因为从谷歌我只想要第一个元素.我的解决方案做到了这一点,但它对我来说似乎不是很有效或很好,它给了我一些错误,不知道为什么……

推荐答案

我认为总的来说,您的代码还不算太差,但还可以稍加改进.很多东西你的IDE可能已经用黄色的曲折下划线指示了,你可以把鼠标悬停在上面看看它是什么.

这是对代码的改进:

fun main() {

    val alist = listOf(
        Person("Alan", "Walker", 23, true, "Google"),
        Person("Bee", "dog", 24, true, "Google"),
        Person("John", "Cena", 25, true, "Google"),
        Person("See", "S", 26, true, "Stackoverflow"),
        Person("Soya", "A", 27, true, "Stackoverflow"),
        Person("Zander", "Cage", 28, true, "Stackoverflow")
    )

    println(alist)

    val uniqueGoogle = alist.first { it.companyName == "Google" }
    val newList = listOf(uniqueGoogle) + alist.filter { it.companyName != "Google" }

    println(newList)
}

EDIT:
A one-liner that would work in your case is:

val newList = alist.distinctBy { if (it.companyName == "Google") true else it.hashCode() }

请注意,如果您的Person类是一个数据类,并且您的列表中也有重复项,那么这将不起作用.或者列表中的多个对象具有相同hashCode()的任何其他情况

Kotlin相关问答推荐

创建具有共同父类型的两种不同类型对象的列表的最有效方法是什么?

如何在Jetpack Compose中的列中渲染图像

数据流弹性模板失败,出现错误&未知非复合转换urn";

使函数同时挂起和取消挂起

从 Kotlin 的父类获取函数注解

为什么 <= 可以应用于 Int 和 Long,而 == 不能?

在协程上下文中重新抛出异常

从字符串列表构建字符串

Kotlin 使用迭代索引过滤 lambda 数组

@InlineOnly 注释是什么意思?

Kotlin 中的 Java Scanner 相当于什么?

如何在调试中修复 ClassNotFoundException: kotlinx.coroutines.debug.AgentPremain?

在粘贴时将 java 转换为 kotlin

Android:在 DAO 中使用 Room 数据库和 LiveData 架构

使用kotlinx协同程序测试中的类时出错

Kotlin-通过与属性列表进行比较来筛选对象列表

这是 Kotlin 中的错误还是我遗漏了什么?

Kotlin:使用自定义设置器时没有lateinit的解决方法?

如果kotlin已经有了getter和setter,为什么在数据类中有componentN函数?

如何在 spring-boot Web 客户端中发送请求正文?