What is the most elegant way to convert a hyphen separated word (e.g. “do-some-stuff”) to the lower camel-case variation (e.g. “doSomeStuff”)?

后端 未结 11 943
清歌不尽
清歌不尽 2020-11-28 07:16

What is the most elegant way to convert a hyphen separated word (e.g. \"do-some-stuff\") to the lower camel-case variation (e.g. \"doSomeStuff\") in Java?

11条回答
  •  遥遥无期
    2020-11-28 07:53

    In case you use Spring Framework, you can use provided StringUtils.

    import org.springframework.util.StringUtils;
    
    import java.util.Arrays;
    import java.util.stream.Collectors;
    
    public class NormalizeUtils {
    
        private static final String DELIMITER = "_";    
    
        private NormalizeUtils() {
            throw new IllegalStateException("Do not init.");
        }
    
        /**
         * Take name like SOME_SNAKE_ALL and convert it to someSnakeAll
         */
        public static String fromSnakeToCamel(final String name) {
            if (StringUtils.isEmpty(name)) {
                return "";
            }
    
            final String allCapitalized = Arrays.stream(name.split(DELIMITER))
                    .filter(c -> !StringUtils.isEmpty(c))
                    .map(StringUtils::capitalize)
                    .collect(Collectors.joining());
    
            return StringUtils.uncapitalize(allCapitalized);
        }
    }
    

提交回复
热议问题