3

I have a code here that's checking if a record's title contains one of the four values that we want to ignore. If the title contains the 4 strings, we would like to put it in the database and set the state to IGNORE. If it doesn't, we still want to put it in the database and set the state to NEW for later processing.

The code works, however, it is a bit of an eye sore. How could I write this in a cleaner, more efficient, easier to read way?

 if (
    record.getTitle().contains("word") ||
    record.getTitle().contains("different word") ||
    record.getTitle().contains("phrase") ||
    record.getTitle().contains("different phrase")
  ) {
    int id = dao.insert(nv);
    nvRecord =
      NV
        .builder()
        .from(nv)
        .setId(id)
        .setState(state.IGNORE)
        .build();
  } else {
    int id = dao.insert(nv);
    nvRecord =
      NV
        .builder()
        .from(nv)
        .setId(id)
        .setState(state.NEW)
        .build();
  }

1 Answer 1

4

You could use a regular expression for "Title" followed by one, two, three or four. Like,

if (record.getTitle().matches("Title [1234]")) {

Or compile a Pattern and use a Matcher like

Pattern p = Pattern.compile("Title [1234]");
Matcher m = p.matcher(title);
if (m.matches()) {

Based on your updated requirements, stream a List of your special titles and check if the record title contains it. Like,

if (List.of("Titanic", "The Great Gatsby", "Catch Me If You Can", "Inception")
        .stream().anyMatch(record.getTitle()::contains))
Sign up to request clarification or add additional context in comments.

5 Comments

You don't need | inside a character class. Should be [1234] or [1-4].
@khelwood Good point. I wasn't thinking about that part (clearly).
Thank you for your answer! I forgot to specify that the titles are vastly different from one another and do not follow a pattern. For example: "Titanic", "The Great Gatsby", "Catch Me If You Can", "Inception"
if (List.of("Titanic", "The Great Gatsby", "Catch Me If You Can", "Inception").stream().anyMatch(record.getTitle()::contains))
Thank you so much! That is a lot cleaner!

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.