StringJoiner与String.join()的使用手册

StringJoiner与String.join()的使用手册

theme: csdn
highlight: 工具

1. StringJoiner:

Java 8 有了StringJoiner,发现时觉得真的好用啊,减少了很多代码量,让自己代码更加简洁明了。
StringJoiner的父类就是 Object

成员变量:
prefix:拼接后的字符串前缀
delimiter:拼接时的字符串分隔符
suffix:拼接后的字符串后缀
value:拼接后的值
emptyValue:空值的情况
value为 null 时返回
StringJoiner的字符串拼接也是基于StringBuilder进行字符拼接的:
/**
     * Adds the contents of the given {@code StringJoiner} without prefix and
     * suffix as the next element if it is non-empty. If the given {@code
     * StringJoiner} is empty, the call has no effect.
     *
     * <p>A {@code StringJoiner} is empty if {@link #add(CharSequence) add()}
     * has never been called, and if {@code merge()} has never been called
     * with a non-empty {@code StringJoiner} argument.
     *
     * <p>If the other {@code StringJoiner} is using a different delimiter,
     * then elements from the other {@code StringJoiner} are concatenated with
     * that delimiter and the result is appended to this {@code StringJoiner}
     * as a single element.
     *
     * @param other The {@code StringJoiner} whose contents should be merged
     *              into this one
     * @throws NullPointerException if the other {@code StringJoiner} is null
     * @return This {@code StringJoiner}
     */
    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;
    }
StringJoiner的使用方式:
    /**
     * StringJoiner的使用 简单且实用
     */
    void stringJoinerTest() {
    
    
		StringJoiner stringJoiner = new StringJoiner(",","[","]");
		stringJoiner.add("1");
		stringJoiner.add("2");
		stringJoiner.add("3");
		stringJoiner.add("4");
		stringJoiner.add("5");
		System.out.println(stringJoiner);
	}
    /**
     * StringJoiner的构造方法
     *
     * 构造一个没有字符的{@code StringJoiner}
     * {@code prefix} or {@code suffix}, and a copy of the supplied
     * {@code delimiter}.
     * 如果没有向{@code StringJoiner}和方法添加字符*访问它的值被调用时,它不会返回a
     * {@code前缀}或{@code后缀}(或其属性),*除非{@code setEmptyValue}已被首次调用。
     *
     * @param  delimiter the sequence of characters to be used between each
     *         element added to the {@code StringJoiner} value
     * @throws NullPointerException if {@code delimiter} is {@code null}
     */
    public StringJoiner(CharSequence delimiter) {
    
    
        this(delimiter, "", "");
    }

    /**
     * 使用副本构造一个没有字符的{@code StringJoiner}*提供的{@code前缀}、{@code分隔符}
     * 和{@code后缀}。
     * 如果{@code StringJoiner}和方法中没有添加字符*访问它的字符串值时,它将返回
     * {@code前缀+后缀}(或其属性),除非
     * {@code setEmptyValue}首次被调用。
     *
     * @param  delimiter the sequence of characters to be used between each
     *         element added to the {@code StringJoiner}
     * @param  prefix the sequence of characters to be used at the beginning
     * @param  suffix the sequence of characters to be used at the end
     * @throws NullPointerException if {@code prefix}, {@code delimiter}, or
     *         {@code suffix} is {@code null}
     */
    public StringJoiner(CharSequence delimiter,
                        CharSequence prefix,
                        CharSequence suffix) {
    
    
        Objects.requireNonNull(prefix, "The prefix must not be null");
        Objects.requireNonNull(delimiter, "The delimiter must not be null");
        Objects.requireNonNull(suffix, "The suffix must not be null");
        // make defensive copies of arguments
        this.prefix = prefix.toString();
        this.delimiter = delimiter.toString();
        this.suffix = suffix.toString();
        this.emptyValue = this.prefix + this.suffix;
    }

2. String.join():

Java 8 同样有了String.join(),是基于StringJoiner进行字符串组合,减少了更多代码量,让自己代码更加简洁明了。
    /**
     * JAVA 8 出现的新方法 join()
     *
     * 属性的副本组成的新字符串
     * {@code CharSequence元素}与的副本连接在一起*指定的{@code分隔符}。
     *
     * <blockquote>For example,
     * <pre>{@code
     *     String message = String.join("-", "Java", "is", "cool");
     *     // message returned is: "Java-is-cool"
     * }</pre></blockquote>
     *
     * Note that if an element is null, then {@code "null"} is added.
     *
     * @param  delimiter the delimiter that separates each element
     * @param  elements the elements to join together.
     *
     * @return a new {@code String} that is composed of the {@code elements}
     *         separated by the {@code delimiter}
     *
     * @throws NullPointerException If {@code delimiter} or {@code elements}
     *         is {@code null}
     *
     * @see java.util.StringJoiner
     * @since 1.8
     */
    public static String join(CharSequence delimiter, CharSequence... elements) {
    
    
        Objects.requireNonNull(delimiter);
        Objects.requireNonNull(elements);
        // Number of elements not likely worth Arrays.stream overhead.
        StringJoiner joiner = new StringJoiner(delimiter);
        for (CharSequence cs: elements) {
    
    
            joiner.add(cs);
        }
        return joiner.toString();
    }
    
    /**
     * JAVA 8 出现的新方法 join()
     *
     * 属性的副本组成一个新的{@code字符串}
     * {@code CharSequence元素}与
     * 指定{@code分隔符}。
     *
     * <blockquote>For example,
     * <pre>{@code
     *     List<String> strings = new LinkedList<>();
     *     strings.add("Java");strings.add("is");
     *     strings.add("cool");
     *     String message = String.join(" ", strings);
     *     //message returned is: "Java is cool"
     *
     *     Set<String> strings = new LinkedHashSet<>();
     *     strings.add("Java"); strings.add("is");
     *     strings.add("very"); strings.add("cool");
     *     String message = String.join("-", strings);
     *     //message returned is: "Java-is-very-cool"
     * }</pre></blockquote>
     *
     * Note that if an individual element is {@code null}, then {@code "null"} is added.
     *
     * @param  delimiter a sequence of characters that is used to separate each
     *         of the {@code elements} in the resulting {@code String}
     * @param  elements an {@code Iterable} that will have its {@code elements}
     *         joined together.
     *
     * @return a new {@code String} that is composed from the {@code elements}
     *         argument
     *
     * @throws NullPointerException If {@code delimiter} or {@code elements}
     *         is {@code null}
     *
     * @see    #join(CharSequence,CharSequence...)
     * @see    java.util.StringJoiner
     * @since 1.8
     */
    public static String join(CharSequence delimiter,
            Iterable<? extends CharSequence> elements) {
    
    
        Objects.requireNonNull(delimiter);
        Objects.requireNonNull(elements);
        StringJoiner joiner = new StringJoiner(delimiter);
        for (CharSequence cs: elements) {
    
    
            joiner.add(cs);
        }
        return joiner.toString();
    }
String.join()使用方法:
	/**
	 * String.join()的使用
	 */
       @Test
	void string_JoinerTest() {
    
    
		String str = String.join("|", "1", "2", "3");
		System.out.println(str);

		List<String> list = new ArrayList<String>();
		list.add("1");
		list.add("2");
		list.add("3");
		list.add("4");
		String join = String.join(",", list);
		System.out.println(join);
	}

3. StringJoiner 与 String.join() 关系:

String.join() 这是针对 StringJoiner 又封装了一层的 API,同样出自 Java 8,可以传入动态参数或者迭代器。可根据不同的场景使用不同的工具。
牛牛的库:https://github.com/linzhiqiang007/community_services.git

猜你喜欢

转载自blog.csdn.net/weixin_43869435/article/details/110481478