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();
}
CodePudding user response:
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))