0

I have two record in the database with all the columns the same, the only columns which make difference between the two is a column called txnCo. So the column which is inserted the next will have a higher value and I want to get the last one which is higher. In mysql I can use max function, but in Java I can not use math.max since these are not numbers. So does anyone have any suggestion how to do it in the best way?

I am thinking of using the valueOf function for each string and comparing the two.

Shaun
  • 2,446
  • 19
  • 33
HMdeveloper
  • 2,772
  • 9
  • 45
  • 74
  • 1
    What does the "max" of two strings mean anyway? (Lexicographic sort order? Note that by that comparison, "50" is bigger than "100".) What is the content of this field? If it really contains numbers, your schema should reflect that. – Jon Skeet May 03 '16 at 17:08
  • Please add some example values and show how they should compare. – hyde May 03 '16 at 17:20

1 Answers1

2
strA.compareTo(strB);

is what you are looking for.

If the value is < 0, the first string is lexicographically in front of the second. > 0, the second is in front. = 0, they are equal.

String.compareTo() in the Java API docs.

It is also described in the question How do I compare strings in Java?

Caution tho - it may not be defined in exactly the same way as your SQL comparison, depending on encodings, etc.

If you put all of your strings in any ordered collection (say a TreeSet), you can then just extract the first/last as usual, the collections "know" about the natural order of the strings.

TreeSet<String> set = new TreeSet<>();
set.add("string1");
set.add("string2");
// ... //
String minString = set.first();
String maxString = set.last();
Community
  • 1
  • 1
BadZen
  • 4,083
  • 2
  • 25
  • 48