How to use Java stream map with filters and optional?
Solution 1:
By reducing your problem down I just realized that you always want the value of query.getSystem()
to be the context, therefore:
I reduced your code like this:
MockDbTypeEnum newMethod(MockQuery query, MockDbContextHolder dbContextHolder) {
return Optional
.ofNullable(query.getSystem())
.map(MockDbTypeEnum::valueOf)
.orElse(null);
}
MockDbTypeEnum oldMethod(MockQuery query, MockDbContextHolder dbContextHolder) {
if (Objects.nonNull(query.getSystem())) {
if (!query.getSystem().equals(dbContextHolder.getCurrentDb().toString())) {
dbContextHolder.setCurrentDb(Enum.valueOf(MockDbTypeEnum.class, query.getSystem()));
}
return dbContextHolder.getCurrentDb();
}
return null;
}
Also here are the mocks and tests I used to prove these methods are functionally the same for your purposes:
@ParameterizedTest
@CsvSource(value = {
"PSQL, PSQL, PSQL",
"PSQL, SQL, PSQL",
"SQL, SQL, SQL",
"SQL, PSQL, SQL",
"null, SQL, null",
"null, PSQL, null"
}, nullValues = {"null"})
void test(String system, MockDbTypeEnum currentDb, MockDbTypeEnum expectedResult) {
MockQuery query = new MockQuery(system);
MockDbContextHolder dbContextHolder = new MockDbContextHolder(currentDb);
MockDbTypeEnum result = oldMethod(query, dbContextHolder);
assertEquals(expectedResult, result);
MockDbTypeEnum newResult = newMethod(query, dbContextHolder);
assertEquals(expectedResult, newResult);
}
enum MockDbTypeEnum {
PSQL,
SQL
}
static class MockQuery {
private final String system;
public MockQuery(String system) {
this.system = system;
}
public String getSystem() {
return system;
}
}
static class MockDbContextHolder {
private MockDbTypeEnum currentDb;
public MockDbContextHolder(MockDbTypeEnum currentDb) {
this.currentDb = currentDb;
}
public MockDbTypeEnum getCurrentDb() {
return currentDb;
}
public void setCurrentDb(MockDbTypeEnum currentDb) {
this.currentDb = currentDb;
}
}
Here is the result: