-2

would you please let me know the reason why I am getting the output mentioned below?? I expected to get the following out put:

[Person(_name=xyz4, _age=30),   
Person(_name=xyz5, _age=50)]

because of distinct operator

Main:

fun main(args: Array<String>) {
val person1 = Person("xyz1", 10);
val person2 = Person("xyz2", 20);
val person3 = Person("xyz3", 30);
val person4 = Person("xyz4", 30);
val person5 = Person("xyz5", 50);

var persons = listOf(
person1, person2, person3, person4 , person5)
.asSequence()
.filter { x-> x.age >=30 }
.distinct()

println(persons.toList())
}

output:

[Person(_name=xyz3, _age=30), Person(_name=xyz4, _age=30), 
Person(_name=xyz5, _age=50)]
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

1

you can use

.distinctBy { it.age }

instead of

.distinct()

if order of elements is important you can add sortedBy like this

fun main(args: Array<String>) {
    val person1 = Person("xyz1", 10)
    val person2 = Person("xyz2", 20)
    val person3 = Person("xyz3", 30)
    val person4 = Person("xyz4", 30)
    val person5 = Person("xyz5", 50)

    val persons = listOf(
            person1, person2, person3, person4, person5)
            .reversed()
            .filter { x -> x.age >= 30 }
            .distinctBy { it.age }
            .sortedBy { it.age }

    println(persons.toList())
}