Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return an item by id

I got this piece of code, I am learning from tutorial. I want to return an element by url which looks like clients/1 instead of clients?id=1. How can I achieve this? Also, can the code below be made easier way?

    @GetMapping
    public Client getClient(@RequestParam int id) {
        Optional<Client> first = clientList.stream().filter(element -> element.getId() == id).findFirst();
        return first.get();
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You may want to use @PathVariable as follows:

@Controller
@RequestMapping("/clients")
public class MyController {

    @GetMapping("/{id}")
    public Client getClient(@PathVariable int id) {
        return clientList.stream().filter(element -> element.getId() == id).findFirst().orElseThrow();
    }

Please note, the Optional can be unpacked with orElseThrow method. This will throw a NoSuchElementException in case there is no element found for the id.

Other solution would be to use orElse(new Client(...)) to return a default value if nothing is found.

get() is not really recommended to be used. From the JavaDoc of the get() method:

API Note:
The preferred alternative to this method is orElseThrow().

Even though get() may also throw a NoSuchElementException, similar to orElseThrow, usually the consensus is that get should not be used without isPresent, or should not be used at all. There several other methods to unpack the Optional without forcing you write an if.

The whole idea of the Optional is to overcome this by forcing you to think about the case when there is no value inside.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading