kotlin: distinct/distinctBy函数:给列表去重

一,功能

distinct 返回仅包含给定集合中不同元素的列表。
在给定集合的相同元素中,只有第一个元素会出现在结果列表中。
结果列表中的元素与它们在源集合中的顺序相同。

distinctBy 是 Kotlin 中的一个函数,它允许你根据特定的键或属性对列表进行去重。
它会保留第一次出现的元素,后续重复的元素将被过滤掉。

二,例子

代码:

        //处理按钮点击事件
        binding.button1.setOnClickListener {
            val list = listOf('a', 'A', 'b', 'B', 'A', 'a')
            println("去重后:"+list.distinct()) // [a, A, b, B]
            //按转为大写的字符去重
            println("按转为大写字符去重后:"+list.distinctBy { it.uppercaseChar() }) // [a, b]


            val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
            //按除2后的余数做去重
            val distinctByEvenOdd = numbers.distinctBy { it % 2 }
            println("按除2后的余数去重后:"+distinctByEvenOdd)
        }

运行结果:

image

三,例子

代码:

        //处理按钮点击事件
        binding.button2.setOnClickListener {
            //按指定属性去重
            val ss = listOf(MyData(1, "zhang"), MyData(2, "zhang"), MyData(3, "phil"), MyData(4, "phil"))
            val array = ss.distinctBy {
                it.name
            }

            println("按指定属性去重后:"+array)

        }

运行结果:

image

四,例子

代码:

        //处理按钮点击事件: array转为list再去重
        binding.button3.setOnClickListener {
            // 员工工号数组(有两个107重复)
            val employeeIds = arrayOf(101, 107, 102, 107, 103) // 改用普通数组

            // 正确姿势:先转为List再施法
            val uniqueIds = employeeIds.toList().distinct()

            println("原始工号:${employeeIds.contentToString()}") // [101, 107, 102, 107, 103]
            println("去重结果:$uniqueIds")                     // [101, 107, 102, 103]
        }

运行结果:

image

五,例子

代码:

        //处理按钮点击事件
        binding.button4.setOnClickListener {

            data class Person(val name: String, val age: Int)

            val people = listOf(
                Person("Alice", 30),
                Person("Alice", 30),
                Person("Bob", 25),
                Person("Alice", 35),
                Person("Charlie", 30),
                Person("Charlie", 30),
            )

            //按多个属性组合后去重
            val distinctPeopleByNameAndAge = people.distinctBy { Pair(it.name, it.age) }

            println("按多个属性去重后:"+distinctPeopleByNameAndAge)
        }

运行结果:

image

 

posted @ 2025-08-23 09:20  刘宏缔的架构森林  阅读(30)  评论(0)    收藏  举报