Skip to content
Advertisement

Filter data on array [closed]

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?

@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:

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:

data.stream()
        .filter(action) 
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement