Search code examples
javastringcomparison

Checking if an attribute is equal to a list of string values


According to a business requirement, I will need not check if the value of an attribute if it equal to a list of given string values. I am wondering what is the better way to do it, in case if someday there is a new value that needs to be added. Should these values be stored in a table?

List<String> values = new ArrayList<>();
values.add("value1");
values.add("value2");
values.add("value3");

if(values.contains(brand){
// if the brand contains the given values
// implement a specific logic
}

Thank you


Solution

  • You could do it like this. If there was a Brand class that returned an immutable list of attributes.

    Brand brand = new Brand(...);
    List<String> values = new ArrayList<>();
    values.add("value1");
    values.add("value2");
    values.add("value3");
    if(brand.getAtrributes().containsAll(values)) {
        // do something.
    }
    

    But imo, it would be better to use an EnumSet and define the attributes as enums.

    enum Attr {VALUE1, VALUE2, VALUE3,VALUE4, VALUE5};
    EnumSet<Attr> attr = EnumSet.of(Attr.VALUE1, Attr.VALUE2, Attr.VALUE3, Attr.VALUE4, Attr.VALUE5);
    
    if(attr.contains(Attr.VALUE1)) {
       // do something.
    }
    

    There is still a containsAll method as well as other potentially helpful methods.

    • create a record that takes an set of enums
    • create an instance of that with values 2-4.
    • And use the range feature to verify.
    record Brand(EnumSet<Attr> getAttributes){}
    Brand brand = new Brand(EnumSet.of(Attr.VALUE2,Attr.VALUE3, Attr.VALUE4));
    
    EnumSet<Attr> required = EnumSet.range(Attr.VALUE2,Attr.VALUE4);
    
    if (brand.getAttributes().containsAll(required)) {
        System.out.println("Good to go");
    }
    

    Prints

    Good to go.