[英]java get sub list from a list of objects
有一个依赖清单
家属包含
String emp_Id, name etc,
List<Dependent> dependentList;
dependentList包含员工的所有相关信息。
如何通过提供emp_Id获得受抚养者列表?
例如,一个雇员将有2或3个家属。
好吧,我不想循环。
我尝试使用比较器对列表进行二进制搜索,但未返回所需数据。
我已经遍历了员工列表...随后我应该获得特定员工的依赖...什么是最佳和高效的解决方案?
仅当根据比较器对列表进行排序时,二进制搜索才有效。 对于未按其他标准排序或未排序的列表,必须对其进行过滤。
如果您要过滤,则建议使用Google Collections (或Google Guava ,它是Google Collections的超集):
Collection<Dependent> filtered = Collections2.filter(dependentList, new Predicate<Dependent>() {
public boolean apply(Dependent from) {
return from != null && from.getId().equals(id_so_search_for);
}
}
当然,您不限于.equals()
,而是可以根据所需的任何操作进行匹配(例如,通过正则表达式)。
如果搜索一种类型的数据非常重要,而搜索其他任何类型的数据,则将它们存储在Map<kind-of-id, Dependent>
也是一个不错的选择。 您仍然可以使用Map.values()
检索所有存储对象的集合。
如果一个键映射到多个项目,请使用Map<kind-of-id, Collection<Dependent>>
或(最好)考虑使用现有的Multimap功能: com.google.common.collect.Multimap或org.apache.commons .collections.MultiMap (请注意,Apache Commons没有通用版本)。
您想建立关系模型。 我想,您具有基本的依赖关系:
因此,一个非常基本的实现可以像这样:
public class Employee {
int emp_id;
// more fields, more methods
}
public class Supervisor extends Employee {
private List<Employee> dependants = new ArrayList<Employee>();
// more fields, more methods
public List<Employee> getDependants() {
return dependants;
}
}
public class StaffDirectory {
private Map<Integer, Employee> staff = new HashMap<Integer, Employee>();
public static List<Employee> getAllDependantsOf(int employeeId) {
Employee employee = staff.get(employeeId);
if (employee instanceof Supervisor) {
return ((Supervisor) employee).getDependants());
} else {
return Collections.emptyList();
}
}
}
你试过什么了? 你有写东西吗?
这是一个一般的猜测:
int employeeToFind = 10;//the id to search for
for(Dependant dep : dependentList ) {
if(dep.getEmployeeId() == employeeToFind) {
//do something
}
}
您也可以将依赖项存储在Hashtable<Integer employeeId,List<Dependent>>();
由EmployeeId键控,以便于查找。
正如alzoid所述,HashMap或HashTable是完成此任务的理想数据结构。 如果您有机会将Dependent实例加载到此类对象中,请这样做。 仍然,有这个美味的代码:
String emp_Id //IDs are usually integer, but I'll go with your example
List<Dependent> dependentList; //assume this is populated
List<Dependent> desiredSublist = new ArrayList<Dependent>();
for(Dependent dep:dependentList){
//make sure to compare with equals in case of Id being String or Integer
if(dep.getId().equals(emp_Id)){
desiredSubList.add(dep);
}
}
//desiredSublist now contains all instances of Dependent that belong to emp_Id.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.