我有一个 rest 服务,它将返回对象的 List
public class MyObject {
private String name;
private String state;
}
现在,我需要根据 rest 调用中提供的字段从列表中过滤对象:
http://localhost:8080/myuri?state=NY
现在,我需要开发自定义过滤器,但我只找到了 property filter不是我想要的东西。有没有办法实现这一目标。
最佳答案
您不需要使用 Jackson
来执行此操作。只需使用 Stream API
过滤它。如果数据是从 DB
加载的,则使用 SQL
的 WHERE
子句对其进行过滤。
例子:
@GetMapping(value = "/states", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<MyObject> loadStates(@RequestParam(name = "state", defaultValue = "NY", required = false) String[] states) {
return service.loadAndFilterByState(states);
}
如果你有一个缓存列表,你可以像下面这样过滤它:
@GetMapping(value = "/states", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public List<MyObject> loadStates(@RequestParam(name = "state", defaultValue = "NY", required = false) String[] states) {
Arrays.sort(states);
return getStates()
.stream()
.filter(s -> Arrays.binarySearch(states, s.getState()) > -1)
.collect(Collectors.toList());
}
另见:
关于java - 根据属性值 spring boot 从列表中过滤对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57258475/