1

I have a rest service that will return List of objects

public class MyObject {
    private String name;
    private String state;
}

Now, I need to filter object from list based on fields provided on rest call:

http://localhost:8080/myuri?state=NY

Now, I need to develop custom filter and I did only find property filter not something like I want. Is there a way to achieve this.

1
  • You want to filter your response from the service? Commented Jul 29, 2019 at 17:44

1 Answer 1

3

You do not need to use Jackson to do this. Just filter it using Stream API. If data, are loaded from DB, filter it using SQL's WHERE clause.

Example:

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

If you have a cached list, you can filter it like below:

@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());
}

See also:

Sign up to request clarification or add additional context in comments.

5 Comments

state could be 0 to many so i was looking something other than java 8 way.
@user9735824, what do you mean by 0 to many? Could you give me some examples? How do you store states list?
so uri could be http://localhost:8080/myuri or http://localhost:8080/myuri?state=NY&state=CA&state=PA
@user9735824, OK, I understand now. How do you store states in your app. Just in List? Or do you have DB or another store for them?
@user9735824, I updated my answer with example how multiple values can be handled. Could you please specify what you would like to use instead of Java 8 Stream API?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.