Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Java introduced enumerations in version 5. Enumerations provide a safe and clean way to manage constants.

In this quick tutorial, we’ll explore how to compare a String to an enum object.

2. Introduction to the Problem

First of all, let’s see an enum example:

enum Weekday {
    Mon("Monday"),
    Tue("Tuesday"),
    Wed("Wednesday"),
    Thu("Thursday"),
    Fri("Friday"),
    Sat("Saturday");
                                 
    private String fullName;
                                 
    Weekday(String fullName) {
        this.fullName = fullName;
    }
                                 
    public String getFullName() {
        return fullName;
    }
}

As the code above shows, the Weekday enum contains six constants named by each weekday abbreviation. Further, it has a property fullName, to hold each weekday’s complete name.

Now let’s say we’re given a string s. Then comparing s to an enum instance can have two possibilities:

  • comparing s to the enum instance name
  • comparing s to one String property of the enum instance

This tutorial covers both scenarios. Furthermore, we’ll perform case-insensitive comparisons.

For simplicity, we’ll use unit test assertions to verify the comparison results.

So next, let’s create two Strings as inputs:

final String SAT = "sAt";
final String SATURDAY = "sAtuRdAy";

We’ll use the SAT string for the enum name comparison and the SATURDAY variable for the enum‘s property comparison. To make it complete, let’s create another two Strings for negative tests:

final String TYPO_FRI = "ffri";
final String TYPO_FRIDAY = "ffriday";

After we understand how to compare a String and an enum instance, we’ll also discuss the common use case of these comparisons. So next, let’s see them in action.

3. Comparing a Given String to an enum Instance’s Name or Property

First, let’s look at comparing the given String to the enum instance’s name.

All enum classes inherit the abstract java.lang.Enum class. This abstract class defines the name() method to return an enum instance’s name:

public abstract class Enum<E extends Enum<E>> implements Constable, Comparable<E>, Serializable {
    private final String name;
    ...

    public final String name() {
        return this.name;
    }
...

Therefore, we can use the name() method to get the enum constant’s name and compare it to the given String:

assertTrue(SAT.equalsIgnoreCase(Sat.name()));
assertFalse(TYPO_FRI.equalsIgnoreCase(Fri.name()));

As the test above shows, we’ve used the equalsIgnoreCase() method for the case-insensitive comparison.

We’ve mentioned that depending on the requirement, we may want to compare a String to the enum constant’s property, such as the fullName property in Weekday. This isn’t difficult as the Weekday enum has a getter method to get the property’s value:

assertTrue(SATURDAY.equalsIgnoreCase(Sat.getFullName()));
assertFalse(TYPO_FRI.equalsIgnoreCase(Fri.getFullName()));

So, as we have seen, no matter which scenario, comparing a String to an enum is pretty straightforward.

But when will we need this comparison in practice? Let’s talk about that through examples.

4. Finding the enum Instance by Its Name and Property

A common use case that needs the comparison would be determining an enum instance by a given String. For example, we want to find the Weekday.Sat constant by the string “SAT”.

So next, let’s add two “find” methods in our Weekday enum:

enum Weekday {
    Mon("Monday"),
    ...

    static Optional<Weekday> byNameIgnoreCase(String givenName) {
        return Arrays.stream(values()).filter(it -> it.name().equalsIgnoreCase(givenName)).findAny();
    }

    static Optional<Weekday> byFullNameIgnoreCase(String givenFullName) {
        return Arrays.stream(values()).filter(it -> it.fullName.equalsIgnoreCase(givenFullName)).findAny();
    }
   ...
}

The two methods’ implementations are pretty similar. One is for finding by name, and the other is for finding by the fullName property.

We’ve used the Stream API in the implementation. First, values() is a static method. Moreover, it’s available in any enum type and returns an array of all enum constants of the corresponding enum type. Therefore, Weekday.values() gives us all Weekday constants.

Then, we convert the constant array into a Stream object. Next, we pass the case-insensitive comparison logic to the filter() method as a lambda expression.

As we don’t know if the filter() method can find a matched enum instance, we return the findAny() method’s result, which is an Optional<Weekday> object.

The method caller can decide the next move by checking this Optional result. Next, let’s see how it works in a test method:

Optional<Weekday> optResult = Weekday.byNameIgnoreCase(SAT);
assertTrue(optResult.isPresent());
assertEquals(Sat, optResult.get());
                                                                  
Optional<Weekday> optResult2 = Weekday.byNameIgnoreCase(TYPO_FRI);
assertFalse(optResult2.isPresent());

As the test above shows, only if byNameIgnoreCase() finds a constant, the Optional result’s isPresent() returns true.

It would be quite similar to the “find the enum constant by a property” scenario. Let’s create a test for the byFullNameIgnoreCase() method for completeness:

Optional<Weekday> optResult = Weekday.byFullNameIgnoreCase(SATURDAY);
assertTrue(optResult.isPresent());
assertEquals(Sat, optResult.get());
                                                                         
Optional<Weekday> optResult2 = Weekday.byFullNameIgnoreCase(TYPO_FRIDAY);
assertFalse(optResult2.isPresent());

5. Conclusion

In this article, we’ve learned how to compare a String to an enum constant. Further, we’ve discussed the common use case of the comparisons through examples.

As usual, all code snippets presented here are available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.