如何按对象属性将列表拆分为较小列表的列表



因此,我正试图找到最有效的方法,将对象列表按属性拆分为一个较小的列表,然后将该列表添加到一个新列表中,这听起来很困惑,但如果你阅读了代码,我想你会理解

class Test {
@Test
private fun printEmployeesInShipping(){
val employeesByDepartment = getEmployeesByDepartment()
for (department in employeesByDepartment) {
if(department.get(0).department.equals("Shipping")){
for (employee in department) println("Name:$employee")
}
}
}
private fun getEmployeesByDepartment(): List<List<Employee>>{
val listOfEmployee = ArrayList<Employee>()
listOfEmployee.add(Employee("Bob", "Shipping"))
listOfEmployee.add(Employee("Stacy", "Shipping"))
listOfEmployee.add(Employee("Tom", "Sales"))
listOfEmployee.add(Employee("John", "Sales"))
listOfEmployee.add(Employee("Jim", "Accounting"))
listOfEmployee.add(Employee("Kim", "Accounting"))
//What is the most efficient way to split this list into separate lists and return it
}
}
data class Employee (
val name: String? = null,
val department:String? = null
) 

只需执行:

private fun getEmployeesByDepartment(): List<List<Employee>>{
// [ ... ]
return listOfEmployee.groupBy { it.department }.map { it.value }
}

最新更新