I realize that the results for string1.compareTo(string2) will be a number -1 or below if string2 comes before string1 alphabetically, and a number 1 or above if different the other direction. I need to return only -1, 0, or 1.
I can code it in a seemingly clunky way, but I feel like there must be a more efficient/elegant way to do this. Any help would be appreciated!
String s1 = "aardvark";
String s2 = "zebra";
int c = s1.compareTo(s2); // -25
if (c > 0) {
c = 1;
} else if (c < 0) {
c = -1;
}
Is there some sort of mathematical operation that will change all positive integers to 1 and all negative integers to -1?
EDIT: I have to say, I'm gratified just to have asked a question that wasn't downvoted and deleted, but the prompt and intelligent responses are wonderful. Here are the answers I've tested so far. I wanted to share my results with those who come later.
My test code: (runs each solution about 2600 times at different values)
String s1 = "";
String s2 = "m";
for (int i = 0; i < 100; i++) {
for (char j = 'a'; j < 'z'; j++) {
s2 = ("" + j);
solution1(s1.compareTo(s2));
}
}
My original code: ~1.5ms
if (c > 0) {
c = 1;
} else if (c < 0) {
c = -1;
}
Solution 1: ~4ms
c = (int) Math.signum(c);
Solution 2: ~2ms
c = c > 0 ? 1 : c < 0 ? -1 : 0;
Solution 3: ~2ms
c = Math.max(-1, Math.min(1, c));
Solution 4: ~2ms
c = Integer.compare(c, 0);
I like them all better than my original, so thank you all collectively. Solution 4 gets the check mark due to speed and readability, so thank you especially.
It's actually very simple:
return Integer.compare(s1.compareTo(s2), 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With