Search code examples
javacollectionsjava-streamcamelcasing

Java - check if under_score string is in a list of lowerCamel strings


Consider the following keys (under_score) and fields (lowerCamel):

keys   = ["opened_by","ticket_owner","close_reason"]
fields = ["openedBy","ticketOwner","closeReason"]

I'm looking for an efficient way in Java to check whether key is in fields, where I expect the following to return true:

fields = ["openedBy","ticketOwner"]

return fields.contains("opened_by"))   //true

My code:

Set<String> incidentFields = Arrays
            .stream(TicketIncidentDTO.class.getDeclaredFields())
            .map(Field::getName)
            .collect(Collectors.toSet()
            );


responseJson.keySet().forEach(key ->{
           
            if (incidentFields.contains(key)) 
            {
                //Do something
            }
        });

I could just replace all lowerCase with underscore, but I'm looking for more efficient way of doing this.


Solution

  • If you do not have fields like abcXyz (abc_xyz) and abCxyz (ab_cxyz) (fields with same spelling but combination of different words), then one solution would be to replace the "_" with empty "" and then compare to fieldName using equalsIgnoreCase. Another but similar solution would be to convert each fieldName to lower case and then compare it to the camel case string after replacing the "_" with "". This could possibly eliminate the use of an additional loop when compared to the first approach.

    
    Set<String> fields= Arrays.stream(TicketIncidentDTO.class.getDeclaredFields())
                              .map(Field::getName)
                              .map(String::toLowerCase)
                              .collect(Collectors.toSet());
    
    
    responseJson.keySet()
                .filter(key -> fields.contains(key.replaceAll("_","")))
                .forEach(key -> {
                    // do something..
                });