Reputation: 1603
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
Upvotes: 4
Views: 3583
Reputation: 89578
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
)
}
Upvotes: 5
Reputation: 7648
make Employee
extends another class, put the properties that you want to keep in the superclass. Instead of List<Employee>
, create a List of that superclass. For example:
calss A
{
int propToKeep;
}
class B extends A
{
@Override
int propToKeep;
int propToDrop;
}
Then you can create a List<A>
out of a bunch of B
Upvotes: 0