我有一個要求,即必須根據多個動態過濾器條件從列表中過濾對象。如果過濾器條件是多個且動態過濾,則從列表中過濾對象
我已經通過遍歷對象編寫了代碼,然後全部過濾,並在任何條件不匹配時返回false。我寫的代碼是
Map<String, String> obj1 = new HashMap<>();
obj1.put("id", "1");
obj1.put("name", "name1");
obj1.put("dept", "IT");
obj1.put("sex", "M");
Map<String, String> obj2 = new HashMap<>();
obj2.put("id", "2");
obj2.put("name", "name2");
obj2.put("dept", "IT");
obj2.put("sex", "M");
Map<String, String> obj3 = new HashMap<>();
obj3.put("id", "3");
obj3.put("name", "name3");
obj3.put("dept", "DEV");
obj3.put("sex", "F");
ArrayList<Map<String, String>> employees = new ArrayList<>(Arrays.asList(obj1,obj2,obj3));
Map<String, String> filterCondition = new HashMap<>();
filterCondition.put("dept", "IT");
filterCondition.put("sex", "M");
List<Map<String, String>> filteredEmployee = new ArrayList<>();
for(Map<String,String> employee:employees){
if(isValid(filterCondition, employee)){
filteredEmployee.add(employee);
}
}
System.out.println(filteredEmployee);
的isValid方法爲
private static boolean isValid(Map<String, String> filterCondition, Map<String, String> employee) {
for(Entry<String, String> filterEntry:filterCondition.entrySet()){
if(!employee.get(filterEntry.getKey()).equals(filterEntry.getValue())){
return false;
}
}
return true;
}
有沒有更好的方式來實現它,如果是我收到的過濾器是動態的到來。
我已經看到了計算器爲here一些答案,但沒有幫助
你使用Java 8? – AjahnCharles
我可以使用它。但即使使用流過濾器,我也無法更好地認爲解決方案。 – Roshan
不是一個解決方案,但我會切換條件以避免潛在的NPE:if(!filterEntry.getValue()。equals(employee.get(filterEntry.getKey())))' –