java - Filter object from List if filter condition is multiple and coming dynamically -


i have requirement have filter object list based on multiple dynamic filter condition.

i have written code looping on objects , filter , returning false if condition doesn't match. code have written as

    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 method as

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; } 

is there better way achieve if filters getting coming dynamically.

i have seen answer in stackoverflow here ,but no

combine filters single predicate (using stream, reduce, , predicate composition):

predicate<map<string, string>> allconditions = filtercondition         .entryset()         .stream()         .map(thisclass::getaspredicate)         .reduce((employee) -> true, predicate::and); 

then use stream.filter()

list<map<string, string>> filteredemployees = employees         .stream()         .filter(allconditions)         .collect(collectors.tolist()); 

helper function:

private static predicate<map<string, string>> getaspredicate(map.entry<string, string> filter) {     return (map<string, string> employee) -> employee.get(filter.getkey()).equals(filter.getvalue()); } 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -