I’m trying to filter the userId, name and the age of the user using (>, <, =) operators. I kinda got stuck because I always do this via SQL but in the case I already have the data in a List.
The array has about 1 Million Users but after filtering I will use pagination so don’t worry about the size of the filtered array
Any guidance on how to implement this in a fast way? Is it possible to use the operator on the Collection?
JavaScript
x
@GetMapping("/users")
public ResponseEntity << ? > getUsers(@RequestParam Long userId, @RequestParam Integer age, @RequestParam String name, @RequestParam(defaultValue = "=") String operator) {
List < User > data = userService.getData();
data.stream().filter( ? ? );
return new ResponseEntity < > (data, HttpStatus.OK);
}
Advertisement
Answer
You can create your own process by using if..else or switch..case, of better you create a map with all action needed like this:
JavaScript
Map<String, Predicate<User>> actions = new HashMap<>();
actions.put("=", u -> u.getId() == userId); // or any condition you want
actions.put("<", u -> u.getId() < userId);
actions.put(">", u -> u.getId() > userId);
// You can also check and if not exist throw an exception
Predicate<User> action = actions.getOrDefault(operator, actions.get("="));
data.stream()
.filter(action::test) // <------- apply the action.
..
Or simply as @MarkRotteveel mention, you can simply use action without test:
JavaScript
data.stream()
.filter(action)