You can use a wrapper class overriding equals(Object) and hashCode().
public final class StringWrapper {
private final String value;
private StringWrapper(String value) {
this.value = value;
}
public static StringWrapper ofValue(String value) {
return new StringWrapper(value);
}
public static StringWrapper ofNull() {
return ofValue(null);
}
public static StringWrapper ofEmpty() {
return ofValue("");
}
@Override
public int hashCode() {
if (value == null || value.isEmpty()) {
return 0;
}
return value.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof StringWrapper wrapper)) {
return false;
}
String value1 = Objects.requireNonNullElse(value, "");
String value2 = Objects.requireNonNullElse(wrapper.value, "");
return Objects.equals(value1, value2);
}
@Override
public String toString() {
return "Wrapper - " + value;
}
}
And tests covering the scenarios:
public class StringWrapperTests {
@Test
public void sameStringValues_ShouldReturnTrue() {
StringWrapper first = StringWrapper.ofValue("a");
StringWrapper second = StringWrapper.ofValue("a");
assertEquals(first, second);
assertEquals(second, first);
}
@Test
public void differentValues_ShouldReturnFalse() {
StringWrapper first = StringWrapper.ofValue("a");
StringWrapper second = StringWrapper.ofValue("b");
assertNotEquals(first, second);
assertNotEquals(second, first);
}
@Test
public void bothEmpty_ShouldReturnFalse() {
StringWrapper first = StringWrapper.ofEmpty();
StringWrapper second = StringWrapper.ofEmpty();
assertEquals(first, second);
assertEquals(second, first);
}
@Test
public void firstNullSecondEmpty_ShouldReturnTrue() {
StringWrapper first = StringWrapper.ofNull();
StringWrapper second = StringWrapper.ofEmpty();
assertEquals(first, second);
}
@Test
public void firstEmptySecondNull_ShouldReturnTrue() {
StringWrapper first = StringWrapper.ofEmpty();
StringWrapper second = StringWrapper.ofNull();
assertEquals(first, second);
}
@Test
public void bothNull_ShouldReturnTrue() {
StringWrapper first = StringWrapper.ofNull();
StringWrapper second = StringWrapper.ofNull();
assertEquals(first, second);
assertEquals(second, first);
}
@Test
public void firstNullSecondValue_ShouldReturnFalse() {
StringWrapper first = StringWrapper.ofNull();
StringWrapper second = StringWrapper.ofValue("qwerty");
assertNotEquals(first, second);
}
@Test
public void firstValueSecondNull_ShouldReturnFalse() {
StringWrapper first = StringWrapper.ofValue("asd");
StringWrapper second = StringWrapper.ofNull();
assertNotEquals(first, second);
}
}
return one == null || one.isEmpty()? two == null || two.isEmpty(): one.equals(two);That’s the literal translation of your conditions.