zoukankan      html  css  js  c++  java
  • 工具类系列---【java8新特性-字符串拼接工具StringJoiner类】

    前言:

    StringJoiner是Java8新出的一个类,用于构造由分隔符分隔的字符序列,并可选择性地从提供的前缀开始和以提供的后缀结尾。省的我们开发人员再次通过StringBuffer或者StingBuilder拼接。

    用法示例:

    StringJoiner sj = new StringJoiner(":", "[", "]");
    sj.add("hu").add("jun").add("wei");
    String desiredString = sj.toString();

    输出结果:

    [hu:jun:wei]

    源码分析:

        public String toString() {
            if (value == null) {
                return emptyValue;//没有值将返回空值或者后续设置的空值
            } else {
                if (suffix.equals("")) {
                    return value.toString();//后缀为""直接返回字符串,不用添加
                } else {
                    //后缀不为"",添加后缀,然后直接返回字符串,修改长度
                    int initialLength = value.length();
                    String result = value.append(suffix).toString();
                    // reset value to pre-append initialLength
                    value.setLength(initialLength);
                    return result;
                }
            }
        }
        初始化,先添加前缀,有了之后每次先添加间隔符,StringBuilder后续append字符串
        public StringJoiner add(CharSequence newElement) {
            prepareBuilder().append(newElement);
            return this;
        }
        //合并StringJoiner,注意后面StringJoiner 的前缀就不要了,后面的appen进来
        public StringJoiner merge(StringJoiner other) {
            Objects.requireNonNull(other);
            if (other.value != null) {
                final int length = other.value.length();
                // lock the length so that we can seize the data to be appended
                // before initiate copying to avoid interference, especially when
                // merge 'this'
                StringBuilder builder = prepareBuilder();
                builder.append(other.value, other.prefix.length(), length);
            }
            return this;
        }
        //初始化,先添加前缀,有了之后每次先添加间隔符
        private StringBuilder prepareBuilder() {
            if (value != null) {
                value.append(delimiter);
            } else {
                value = new StringBuilder().append(prefix);
            }
            return value;
        }
    
        public int length() {
            // Remember that we never actually append the suffix unless we return
            // the full (present) value or some sub-string or length of it, so that
            // we can add on more if we need to.
            //不忘添加后缀的长度
            return (value != null ? value.length() + suffix.length() :
                    emptyValue.length());
        }
    }
    愿你走出半生,归来仍是少年!
  • 相关阅读:
    微信小程序音乐播放控制API在真机上貌似不可用?
    微信小程序request合法域名怎么配置啊
    微信小程序的路径是怎么计算的?
    微信小程序微信录音的silk格式文件怎么转MP3
    微信小程序全国巡回沙龙厦门站-尚琳凯演讲详细内容实录
    微信小程序全国巡回沙龙厦门站-A闪演讲详细内容实录
    微信小程序开发指南合集 各类组件用法技巧
    微信小程序常见问题及新手跳坑指南 每日更新 欢迎补充
    微信小程序沙龙回顾 附演讲实录及ppt
    laravel中的form表单提交
  • 原文地址:https://www.cnblogs.com/hujunwei/p/14030283.html
Copyright © 2011-2022 走看看