Answers for "how to compare string and integer in java"

0

string integer compare java

num == Integer.parseInt(str) is going to faster than str.equals("" + num)

str.equals("" + num) will first convert num to string which is O(n) where n being the number of digits in the number. Then it will do a string concatenation again O(n) and then finally do the string comparison. String comparison in this case will be another O(n) - n being the number of digits in the number. So in all ~3*O(n)

num == Integer.parseInt(str) will convert the string to integer which is O(n) again where n being the number of digits in the number. And then integer comparison is O(1). So just ~1*O(n)

To summarize both are O(n) - but str.equals("" + num) has a higher constant and so is slower.
Posted by: Guest on February-27-2021
0

java convert string to int and compare

Collections.sort(data, new Comparator<TXCartData>() {
        @Override
        public int compare(TXCartData lhs, TXCartData rhs) {
            int n1=Integer.parseInt(lhs.rowId);
            int n2=Integer.parseInt(rhs.rowId);
            if (n1>=n2){
                return 1;
            }
            return -1;
        }
    });
Posted by: Guest on April-18-2021

Code answers related to "how to compare string and integer in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language