[Java基础]计算字符串数组内数组总长 (StringUtils.join StringBuilder.append)

本文主要是介绍[Java基础]计算字符串数组内数组总长 (StringUtils.join StringBuilder.append),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言

最近在开发的时候, 需要计算一个String数组, 拼接后的长度. 本来是准备自己写了一个简单的工具类, 计算长度. 经过同事的提醒, 发现还有这样一个好用的工具类.


方法一

    public static int calculateStrJoinLengthOfListMethod1(List<String> strList){if(CollectionUtils.isEmpty(strList)){return 0;}// 数组的join方法 “[Hello,world,abc]”String tmpStr1 = StringUtils.join(strList);// 注意此处我们不希望使用默认的分隔符 "," "HelloWorldAbc"String tmpStr2 = StringUtils.join(strList, "");return tmpStr2.length();}

方法二

    public static int calculateStrJoinLengthOfListMethod2(List<String> strList){if(CollectionUtils.isEmpty(strList)){return 0;}StringBuilder builder = new StringBuilder();strList.forEach(str -> builder.append(str));return builder.toString().length();}

测试方法

package com.yanxml.util.string;import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;import java.util.ArrayList;
import java.util.List;public class StringArrayUtils {public static int calculateStrJoinLengthOfListMethod1(List<String> strList){if(CollectionUtils.isEmpty(strList)){return 0;}// 数组的join方法 “[Hello,world,abc]”String tmpStr1 = StringUtils.join(strList);// 注意此处我们不希望使用默认的分隔符 "," "HelloWorldAbc"String tmpStr2 = StringUtils.join(strList, "");return tmpStr2.length();}public static int calculateStrJoinLengthOfListMethod2(List<String> strList){if(CollectionUtils.isEmpty(strList)){return 0;}StringBuilder builder = new StringBuilder();strList.forEach(str -> builder.append(str));return builder.toString().length();}public static void main(String[] args) {List<String> strList = new ArrayList<>();strList.add("Hello");strList.add("World");strList.add("abc");// 测试方法1int lengthByTest1 = calculateStrJoinLengthOfListMethod1(strList);System.out.println("Test By Method1 - StringUtils.join, length " + lengthByTest1);// 测试方法2int lengthByTest2 = calculateStrJoinLengthOfListMethod2(strList);System.out.println("Test By Method2 - StringBuilder.append, length "+ lengthByTest2);  }
}
# 测试结果Test By Method1 - StringUtils.join, length 13
Test By Method2 - StringBuilder.append, length 13

源码解析

从使用者的角度来说, 正常到这里就应该结束了. 但是, 从实际开发中, 我们都学到了, 遇到问题, 多深入一点, 就会有更好的理解和回报.

我们先仔细看下StringUtils.join方法.

数组的Join方法
 String tmpStr1 = StringUtils.join(strList);
# org.apache.commons.lang3.StringUtils 类# 单参数重载方法 Arraypublic static <T> String join(T... elements) {return join((Object[])elements, (String)null);}# 2个参数重载方法 Array & 间隔符public static String join(Object[] array, String separator) {return array == null ? null : join(array, separator, 0, array.length);}# 4个参数重载方法 Array & 间隔符 & 开始下标 & 结束下标public static String join(Object[] array, String separator, int startIndex, int endIndex) {if (array == null) {return null;} else {if (separator == null) {separator = "";}int noOfItems = endIndex - startIndex;if (noOfItems <= 0) {return "";} else {StringBuilder buf = new StringBuilder(noOfItems * 16);for(int i = startIndex; i < endIndex; ++i) {if (i > startIndex) {buf.append(separator);}if (array[i] != null) {buf.append(array[i]);}}return buf.toString();}}}
  • 可以看到, 这个join方法就是使用的方法二方法一样. 用的StringBuilder.append方法. 只是包装了一层, 并无其他卵用. 并且还是2者都是线程非安全的.

字符串的Join方法
        String tmpStr2 = StringUtils.join(strList, "");
# org.apache.commons.lang3.StringUtilspublic static String join(Iterable<?> iterable, String separator) {return iterable == null ? null : join(iterable.iterator(), separator);}public static String join(Iterator<?> iterator, String separator) {if (iterator == null) {return null;} else if (!iterator.hasNext()) {return "";} else {Object first = iterator.next();if (!iterator.hasNext()) {String result = ObjectUtils.toString(first);return result;} else {StringBuilder buf = new StringBuilder(256);if (first != null) {buf.append(first);}while(iterator.hasNext()) {if (separator != null) {buf.append(separator);}Object obj = iterator.next();if (obj != null) {buf.append(obj);}}return buf.toString();}}}
  • 比较有意思的是, 这2个方法得到的结果是完全不一样的. 最主要的问题, 可能就是在这里的, 数组的迭代是通过一个强制转换上return join((Object[])elements, (String)null); 字符串是使用Iterator进行处理的.

一个奇怪的现象

得到的结果为 “[Hello, World, Abc]”

        // 数组的join方法 “[Hello,world,abc]”String tmpStr1 = StringUtils.join(strList);// 注意此处我们不希望使用默认的分隔符 "," "HelloWorldAbc"String tmpStr2 = StringUtils.join(strList, "");
  • 可能是第一种调用方式, 触发了数组的toString方法, 导致了这里会出现, [XX,XX,XX]这样的展现.

Reference

[1]. [StringUtils.join()方法的方法和使用] (https://www.cnblogs.com/fenghh/p/12175368.html)
[2]. [CollectionUtils属于哪个包] https://blog.csdn.net/weixin_42114097/article/details/90579980

这篇关于[Java基础]计算字符串数组内数组总长 (StringUtils.join StringBuilder.append)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/988152

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

从基础到高级详解Go语言中错误处理的实践指南

《从基础到高级详解Go语言中错误处理的实践指南》Go语言采用了一种独特而明确的错误处理哲学,与其他主流编程语言形成鲜明对比,本文将为大家详细介绍Go语言中错误处理详细方法,希望对大家有所帮助... 目录1 Go 错误处理哲学与核心机制1.1 错误接口设计1.2 错误与异常的区别2 错误创建与检查2.1 基础