zoukankan      html  css  js  c++  java
  • mybatis --- 如何相互转换逗号分隔的字符串和List

     如果程序员想实现某种功能,有两条路可以走。一条就是自己实现,一条就是调用别人的实现,别人的实现就是所谓的API。而且大多数情况下,好多“别人”都 实现了这个功能。程序员有不得不在这其中选择。大部分情况下,程序员就会知道哪个用哪个,先看到哪个用哪个。到最后,在实际项目中,同样的功能会调用五花 八门的API。我在公司的项目中就看到了这种情况。其实,也无可厚非,我相信好多项目都是这个样子。我们不可能要求程序员都用同一种方法。程序员可能会有 不同的好恶。为了让程序员能快乐自由地编程,就随他去吧!因为程序员感觉自由的时候,感觉快乐的时候,正是他们生产力最高的时候。

    不扯淡了。回归正题,到底这些不同的实现方法或者API真的就没有高低贵贱之分?以我遇到这个逗号分隔字符串转List为例,探讨探讨:

    注:下面的代码并不能保证能运行,可能需要稍微的修改。

    将逗号分隔的字符串转换为List

    方法 1: 利用JDK的Arrays类

    String str = "a,b,c";
    List<String> result = Arrays.asList(str.split(","));

    方法 2: 利用Guava的Splitter

        String str = "a, b, c";
        List<String> result = Splitter.on(",").trimResults().splitToList(str);

    方法 3: 利用Apache Commons的StringUtils (只是用了split)

        String str = "a,b,c";
        List<String> result = Arrays.asList(StringUtils.split(str,","));

    方法 4: 利用Spring Framework的StringUtils

        String str = "a,b,c";
        List<String> str = Arrays.asList(StringUtils.commaDelimitedListToStringArray(str));

    将List转换为逗号分隔符

    方法 1: 利用JDK  (好像没有很好的方法,需要一步一步实现)

     NA

    方法 2: 利用Guava的Joiner

        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        String str = Joiner.on(",").join(list);

    方法 3: 利用Apache Commons的StringUtils

        List<String> list = new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("c");
        String str = StringUtils.join(list.toArray(), ",");

    方法 4:利用Spring Framework的StringUtils

    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    String str = StringUtils.collectionToDelimitedString(list, ",");

    比较下来,我的观点就是Guava库更灵活,适用面更广。项目中如果没有引入Guava的话,那就加上它。

      //拼接所有字符串
        public String getAllIdByUserMobile( List<String> userMobile) throws Exception {
               StringBuilder userMobileIdString = new StringBuilder();
               //拼接字符串 userMobile productId
                if( userMobile.size() <= 0){
                    return "";
                }else{
                    for(String item:userMobile){
                        userMobileIdString.append(item + ",");
                    }
                    return org.apache.commons.lang.StringUtils.removeEnd(userMobileIdString.toString(), ",");
                }
    
        }
  • 相关阅读:
    Jenkins 完成安装环境配置
    Jenkins中文社区的所有镜像地址
    VueX源码分析(3)
    VueX源码分析(2)
    VueX源码分析(1)
    Element表单验证(2)
    Element表单验证(1)
    配置淘宝镜像,不使用怪异的cnpm
    React动态import()
    cnpm 莫名奇妙bug 莫名奇妙的痛
  • 原文地址:https://www.cnblogs.com/a8457013/p/9359447.html
Copyright © 2011-2022 走看看