Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KOTLIN/JAVA Remove some properties of an object from List of object

I want to keep only a few properties of an object. Lets say I have List of objects, List<Employee> and Employee data class has some 10 properties. From the List, I would want to keep only 3-4 properties and filter out rest. How can that be achieved in Java or Kotlin? TIA

like image 417
hack Avatar asked Oct 27 '25 21:10

hack


1 Answers

Create separate data classes for your separate use cases:

data class Employee(val id: Long, val name: String, val age: Int, val position: String)
data class PartialEmployee(val id: Long, val name: String)

Then you can map between these as necessary:

val employees: List<Employee> = ...
val partialEmployees: List<PartialEmployee> = employees.map {
    PartialEmployee(
            id = it.id,
            name = it.name
    )
}
like image 60
zsmb13 Avatar answered Oct 29 '25 10:10

zsmb13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!