java String to convert a string List <Long> Type

In some scenarios which, we may encounter the following scenario, the type we want to use the List Type, but the received parameter type is Stirng form such as 1,2,3,4 like
we can complete the above requirements by using the following transcoding

    private static Log log = LogFactory.getLog(Demo.class);

    @Test
    public void test() {
        String ids = "1, 3, 5, 7, 9";
        // 首先去除空格
        String idsWithNoBlank = ids.replaceAll(" +", "");
        // 其次使用分隔符将代码字符分开
        String[] idsNoBlankArray = idsWithNoBlank.split(",");
        // 使用 org.apache.commons.beanutils 提供的工具类进行类型转换
        // gradle 引入:compile group: 'commons-beanutils', name: 'commons-beanutils', version: '1.9.3'
        Long[] convert = (Long[]) ConvertUtils.convert(idsNoBlankArray, Long.class);
        // 然后转换成为 list
        List<Long> idsLong = Arrays.asList(convert);
        log.error(idsWithNoBlank);
        for (Long m : idsLong) {
            log.info(m);
        }
    

Guess you like

Origin www.cnblogs.com/micadai/p/12461954.html