简体   繁体   English

Java - 检查 under_score 字符串是否在 lowerCamel 字符串列表中

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

Consider the following keys (under_score) and fields (lowerCamel):考虑以下键(under_score)和字段(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 :我正在 Java 中寻找一种有效的方法来检查key是否在fields中,我希望以下内容返回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.我可以用下划线替换所有小写,但我正在寻找更有效的方法。

Try with CaseUtils from Commons Text尝试使用Commons Text中的CaseUtils

// opened_by -> openedBy
private String toCamel(String str) {
    return CaseUtils.toCamelCase(str, false, new char[] { '_' });
}

List<String> keys = Arrays.asList("opened_by", "ticket_owner", "close_reason", "full_name");

List<String> fields = Arrays.asList("openedBy", "ticketOwner", "closeReason");

keys.forEach(t -> {
    // check
    if (fields.contains(toCamel(t))) {
        System.out.println(t);
    }
});

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 .如果您没有诸如abcXyz ( abc_xyz ) 和abCxyz ( ab_cxyz ) 之类的字段(具有相同拼写但不同单词组合的字段),那么一种解决方案是将"_"替换为空"" ,然后使用equalsIgnoreCase与 fieldName 进行比较. 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..
            });

A simple toCamel method:一个简单的toCamel方法:

private String toCamel(String str) {
    String[] parts = str.split("_");
    StringBuilder sb = new StringBuilder(parts[0]);
    for (int i=1; i < parts.length ; i++) {
        String part = parts[i];
        if (part.length() > 0) {
            sb.append(part.substring(0, 1).toUpperCase()).append(part.substring(1));
        }
    }
    return sb.toString();
}

Now use the very same approach:现在使用相同的方法:

keys.forEach(t -> {
    if (fields.contains(toCamel(t))) {
        System.out.println("Fields contain " + t);
    } else {
        System.out.println("Fields doesn't contain " + t);
    }
});

I could just replace all lowerCase with underscore, but I'm looking for more efficient way of doing this.我可以用下划线替换所有小写,但我正在寻找更有效的方法。

Use Set as a data structure for keys and fields that is very effective in the look-up.使用Set作为keysfields的数据结构,在查找中非常有效。 Moreover, it is sutable for this use case since it doesn't make sense to have duplicated keys in JSON.此外,它适用于这个用例,因为在 JSON 中有重复的键是没有意义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM