how to write condition for when I send same movie name in postman i will not accept for same movienames

111 Views Asked by At

This is movie class

. I have code for add the movie in postman using post request.

public class Movie {


    private int id;
    private String movieName;
    private String description;
    private String hero;
    private String heroine;

    public Movie(){

    }

    public Movie(int id, String movieName, String description, String hero, String heroine) {
        this.id = id;
        this.movieName = movieName;
        this.description = description;
        this.hero = hero;
        this.heroine = heroine;

    }
//here have setter and getter methods

This is controller class.now what the logic for not accept duplicate moviename

public class MovieController extends Controller {

    public static List<Movie> movies;

    static {
        movies = new ArrayList<>();
        movies.add(new Movie(1, "Fprd vs Ferrari", "Movie on Racing", "abcd", "xyz"));
        movies.add(new Movie(2, "F2", "Comedy Movie", "Venkatesh", "Tamanna"));
        movies.add(new Movie(3, "Titanic", "Movie", "Hero", "Heroine"));
        movies.add(new Movie(4, "Saaho", "action", "Prabhas", "Shradda kapoor"));
        movies.add(new Movie(5, "Bhahubali 1", "action", "Prabhas", "Tamanna"));

    }
 public Result insert(Http.Request request) {
        JsonNode jsonNode = request.body().asJson();
        if (jsonNode == null) {
            return badRequest("insufficient movie information");
        }
        Movie movie = Json.fromJson(jsonNode, Movie.class);
        movies.add(movie);
        return ok(Json.toJson(movie));
    }

This is the Routing for post request

POST        /newmovies              controllers.MovieController.insert(request: Request)
2

There are 2 best solutions below

4
Mushif Ali Nawaz On BEST ANSWER

You can do something like this:

Movie movie = Json.fromJson(jsonNode, Movie.class);

if(movies.stream().noneMatch(m -> m.getMovieName().equals(movie.getName()))) {
    movies.add(movie);
    return ok(Json.toJson(movie));
} else {
    // Movie name already exists... Throw exception here
    return badRequest("Movie already exists");
}
2
Joyal Augustine On

The best way to solve this problem is to override the equals method on Movie object.

@Override
public boolean equals(Object obj) {
if (obj == this) {
        return true;
    }
    if (obj == null || obj.getClass() != this.getClass()) {
        return false;
    }

    Movie movie= (Movie) obj;
    return movie.getMovieName().equals(this.movieName);
}

Here you can define your logic for checking the equality of two movies(Movie name comparison). This approach will be more maintainable

And then simply check whether the list contains the movie in request using

    if (movies.contains(movie)) {
      return badRequest("Movie already exists");
    } 
    movies.add(movie);
    return ok(Json.toJson(movie));