List<JSONObject> myObj = new ArrayList<JSONObject>();
myObj.add(new JSONObject("{"name":"name1","sub-name":"sub-name1", "designation":"d1", "mgr": "m1"}"));
myObj.add(new JSONObject("{"name":"name1","sub-name":"sub-name2", "designation":"d2", "mgr": "m2"}"));
myObj.add(new JSONObject("{"name":"name2","sub-name":"sub-name3", "designation":"d2", "mgr": "m1"}"));
myObj.add(new JSONObject("{"name":"name2","sub-name":"sub-name4", "designation":"d3", "mgr": "m2"}"));
myObj.add(new JSONObject("{"name":"name3","sub-name":"sub-name5", "designation":"d3", "mgr": "m3"}"));
从这个列表中,要求能够根据传递给各种键的值过滤对象。
例如:返回对象
- where name=name1 and mgr=m1
- 名称= d2
- mgr_home_dir_t = m2 where name=name1 or mgr=m1
过滤流可以基于以下条件
List<JSONObject> filterObj = myObj.stream().filter(e -> e.get("name").equals("name1") && e.get("mgr").equals("m1")).collect(Collectors.toList());
我试着看看是否可以构建自定义谓词,但没有太大的成功。
当键和值事先不知道时,如何动态地进行过滤?
对于AND条件有效
List<String> filterConditions = new ArrayList<>();
filterConditions.add("designation:d1");
filterConditions.add("mgr:m1");
List<JSONObject> filterObj = myObj.stream().filter(e -> {
Boolean flag = false;
for (String i : filterConditions) {
if (e.get(StringUtils.substringBefore(i, ":")).equals(StringUtils.substringAfter(i, ":"))) {
flag = true;
} else {
flag = false;
break;
}
}
return flag ? true : false;
}).collect(Collectors.toList());