当我在邮递员中发送相同的电影名称时如何写条件我不会接受相同的电影名称

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

这是电影class

。我有使用 post 请求在 postman 中添加电影的代码。

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

这是控制器class.now不接受重复电影名称的逻辑是什么

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

这是 post 请求

的路由
POST        /newmovies              controllers.MovieController.insert(request: Request)

你可以这样做:

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

解决此问题的最佳方法是覆盖 Movie 对象上的 equals 方法。

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

在这里您可以定义检查两部电影是否相等的逻辑(电影名称比较)。 这种方法将更易于维护

然后使用

简单地检查列表是否包含请求中的电影
    if (movies.contains(movie)) {
      return badRequest("Movie already exists");
    } 
    movies.add(movie);
    return ok(Json.toJson(movie));