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

Viewed 2221

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

2 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
    )
}

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

Related