Java compare values, best way

compareto java
java compare two objects field by field
java comparator
how to compare two different objects in java
java compare numbers
how to write a compareto() method java
java compare string lexicographically
equals() method in java

I has a method like this

private boolean validGrade(final StringBuilder grade) {
   boolean isValid = false;
   String semester = "semester"; 

   if ((grade.toString().contains("2o") && grade.toString().contains(semester))
                    || (grade.toString().contains("4o") && grade.toString().contains(semester))
                    || (grade.toString().contains("6o") && grade.toString().contains(semester))
                    || (grade.toString().contains("8o") && grade.toString().contains(semester))) {
    isValid = true;
            }
    }

And I want to replace it witn something like this:

private boolean doValidGradoAntComp(final StringBuilder grade) {
        boolean isValid = false;

        switch (grade.toString()) {
        case "2o semester":
            isValid = true;
            break;
        case "4o semester":
            isValid = true;
            break;
        case "6o semester":
            isValid = true;
            break;
        case "8o semester":
            isValid = true;
            break;
        default:
            break;
        }

        return isValid;
    }

And my doubt is: which one is better? Both works in the same way?


Why not iterate over the possibilities?

private boolean validGrade(final StringBuilder grade) {
    String gradeString = grade.toString();
    return List.of("2o", "4o", "6o", "8o")
        .stream()
        .map(x -> x + " semester")
        .collect(Collectors.toSet())
        .contains(gradeString);
}

Alternatively, if you're not looking for exact matches, do:

private boolean validGrade(final StringBuilder grade) {
    String gradeString = grade.toString();
    return gradeString.contains("semester") && List.of("2o", "4o", "6o", "8o")
        .stream()
        .anyMatch(gradeString::contains);
}

Finally, if your set of matches is inflexible (will always be "2o", "4o", "6o", "8o"), then you can just use a regular expression:

private boolean validGrade(final StringBuilder grade) {
    return grade.toString().matches("[2468]o semester"); //exact match
//  return grade.toString().matches("[2468]o.*semester|semester.*[2468]o"); //loose match
//  return grade.toString().matches(".*([2468]o.*semester|semester.*[2468]o).*"); //equivalent to contains
}

Java, Method 3: Using compareTo() method. In java Comparable interface compares values and returns an int, these int values may be less than, equal, or greater  The comapre () method of Double Class is a built-in method in Java that compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call.


No both the approaches are different, In the first approach you are using contains to check two string existed in grade (For example 2o and semester in grade). But in the second approche you are checking grade is equal to 2o semester. I prefer collecting all those to list and use anyMatch

List<String> list = List.of("2o","4o","6o","8o");

if(list.stream().anyMatch(val->grade.contains(val) && grade.contains(semester))) {

How compare() method works in Java, We use cookies to ensure you have the best browsing experience on our website​. The compare() method in Java compares two class specific objects (x, of compare() method using Integer Class How is the return value evaluated:. Best part is that BigDecimal numbers are immutable i.e. if you create a BigDecimal BD with value "1.23", that object will remain "1.23" and can never be changed. This class provide many methods which can be used to do numerical operations on it’s value. You can use it’s compareTo() method to compare to BigDecimal numbers. It ignore the scale while comparing.


Comparing Numbers in Java, Comparable ? Comparing the values of two generic Numbers it is generally best to avoid mixed-type computations [] because To compare two Numbers in Java you can use the compareTo method from BigDecimal. How to Compare List Objects in Java 7 vs. Java 8 In this blast from the not-too-distant past, we compare how Java 8's Stream API changed how you can compare List objects. by


Regex may be slower than if-else or switch. But in your case I would put more value on readability and use regex.

private boolean validGrade(final StringBuilder grade) {
    return grade.toString().matches("(2o|4o|6o|8o) semester");
}

Equality and Comparison in Java: Pitfalls and Best Practices, Java has different methods of comparing objects and primitives, each Yes, we can use them to check for equality, and they compare values  UPDATE. If you are willing to invest time in a custom set implementation, there is an approach that can improve the "almost the same" case. The idea is that you need to pre-calculate and cache a hash for the entire set so that you could get the set's current hashcode value in O(1).


Comparing Strings in Java, The compareTo() method returns an int type value and compares two Strings character by character lexicographically based on a dictionary or  Learn to compare two hashmaps in Java by keys, values and key-value pairs. Also learn to compare while allowing or restricting duplicate values. 1. Compare hashmap for same key-values – HashMap.equals() By default, HashMap.equals() method compares two hashmaps by key-value pairs. It means both hashmap instances must have exactly same key-value pairs and both must be of same size.


Comparing Long Values in Java, In this short tutorial, we'll discuss different ways to compare two Long instances. We emphasize the problems that arise when using the  We can compare string in java on the basis of content and reference. It is used in authentication (by equals () method), sorting (by compareTo () method), reference matching (by == operator) etc. There are three ways to compare string in java: By equals () method


Right way to Compare String in Java, In this article, we are going to talk about the right way of comparing String variables, but what is the wrong way? The wrong way is to compare String using​  Description The java.lang.Double.compare () method compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the call − new Double (d1).compareTo (new Double (d2))