Springboot内置的工具类之CollectionUtils示例讲解

前言

实际业务开发中,集合的判断和操作也是经常用到的,Spring也针对集合的判断和操作封装了一些方法,但是最令我惊讶的是,我在梳理这些内容的过程中发现了一些有趣的现象,我的第一反应是不敢相信,再想一想,没错,我是对的。所以强烈建议大家可以认真看完这篇文章,这一篇绝对有价值,因为有趣的是我我竟然发现了Spring的两个bug。

org.springframework.util.CollectionUtils

集合的判断

boolean hasUniqueObject(Collection collection)

从源码注释上看,是用于判断 List/Set 中的每个元素是否唯一,即 List/Set 中不存在重复元素。但这里要告诉大家千万不要用这个方法,因为这个方法有bug,为什么呢?下面是Spring-core-5.2.13.RELEASE.jar中的源码,且看12行,细心的人会发现两个对象之间比较是否相等用的是!=。还记得“==”和“equals”的区别吗?“==”操作符专门用来比较两个变量的值是否相等,equals()方法是用于比较两个独立对象的内容是否相同。所以这里如果集合中的元素是数值,可以用“==”比较,如果是普通的引用对象,就得不到正确的结果了。

public static boolean hasUniqueObject(Collection<?> collection) {
   if (isEmpty(collection)) {
      return false;
   }
   boolean hasCandidate = false;
   Object candidate = null;
   for (Object elem : collection) {
      if (!hasCandidate) {
         hasCandidate = true;
         candidate = elem;
      }
      else if (candidate != elem) {
         return false;
      }
   }
   return true;
}

boolean containsInstance(Collection collection, Object element)

从源码的注释上看,是用于判断集合中是否包含某个对象。这个方法也不建议使用,因为与上一个方法存在相同的问题,且看源码的第4行,依然用的是“==”。

public static boolean containsInstance(@Nullable Collection<?> collection, Object element) {
   if (collection != null) {
      for (Object candidate : collection) {
         if (candidate == element) {
            return true;
         }
      }
   }
   return false;
}

boolean isEmpty(Collection collection)

这个方法已验证过可以放心用,用于判断 List/Set 是否为空;

@Test
public void test1(){
    Collection<String> list=new ArrayList<>();
    boolean empty = CollectionUtils.isEmpty(list);
    Assert.isTrue(empty, "集合list不为空");
    System.out.println("集合list增加一元素");
    list.add("happy");
    boolean empty2 = CollectionUtils.isEmpty(list);
    Assert.isTrue(empty2, "集合list不为空");
}

boolean isEmpty(Map map)

用于判断 Map 是否为空。

@Test
public void test2(){
    Map<String,String> map = new HashMap<>();
    boolean empty = CollectionUtils.isEmpty(map);
    Assert.isTrue(empty, "map不为空");
    System.out.println("map中增加元素");
    map.put("name", "jack");
    boolean empty2 = CollectionUtils.isEmpty(map);
    Assert.isTrue(empty2, "map不为空");
}

boolean containsAny(Collection source, Collection candidates)

从源码上的注释看,是用于判断集合source中是否包含另一个集合candidates的任意一个元素,即集合candidates中的元素是否完全包含于集合soruce。

从源码这个方法中的元素之间的比较用到了“equals”方法,且调用的是集合内对象的equals方法,因此使用这个方法想要得到正确的结果的前提是,比较的对象要重写hashCode()和eauals()方法。

@Test
public void test4(){
    Employee lisi = new Employee("lisi");
    Employee zhangsan = new Employee("zhangsan");
    Employee wangwu = new Employee("wangwu");
    List<Employee > list=new ArrayList<>();
    list.add(zhangsan);
    list.add(lisi);
    List<Employee> list2=new ArrayList<>();
    list2.add(wangwu);
    //这里可以用是因为比较的时候调用的是equals方法
    boolean b = CollectionUtils.containsAny(list, list2);
    Assert.isTrue(b, "list1没有包含有list2中任意一个元素");
}

集合的操作

void mergeArrayIntoCollection(Object array, Collection collection)

将数组array中的元素都添加到 List/Set 中。

@Test
public void test6(){
    List<Employee > list=new ArrayList<>();
    Employee lisi = new Employee("lisi");
    list.add(lisi);
    Employee zhangsan = new Employee("zhangsan");
    Employee[] employees={zhangsan};
    CollectionUtils.mergeArrayIntoCollection(employees, list);
    Assert.isTrue(list.size()==2, "把数据中的元素合并到list失败了");
}

void mergePropertiesIntoMap(Properties props, Map map)

将 Properties 中的键值对都添加到 Map 中。

@Test
public void test7(){
    Properties properties = new Properties();
    properties.setProperty("name", "zhangsan");
    Map<String,String > map = new HashMap<>();
    CollectionUtils.mergePropertiesIntoMap(properties, map);
    Assert.isTrue(map.get("name").equals("zhangsan"), "把properties中的元素合并到map中失败了");
}
@Test
public void test7(){
    Properties properties = new Properties();
    properties.setProperty("name", "zhangsan");
    Map<String,String > map = new HashMap<>();
    CollectionUtils.mergePropertiesIntoMap(properties, map);
    Assert.isTrue(map.get("name").equals("zhangsan"), "把properties中的元素合并到map中失败了");
}

T lastElement(List list)

返回 List 中最后一个元素。

@Test
public void test9(){
    Employee lisi = new Employee("lisi");
    Employee zhangsan    = new Employee("zhangsan");
    List<Employee > list=new ArrayList<>();
    list.add(zhangsan);
    list.add(lisi);
    Employee employee = CollectionUtils.firstElement(list);
    Assert.isTrue(employee.equals(zhangsan), "获取集合第一个元素失败了");

}

T firstElement(List list)

返回集合中第一个元素。

@Test
public void test10(){
    Employee zhangsan    = new Employee("zhangsan");
    Employee[] employees={zhangsan};
    List list = CollectionUtils.arrayToList(employees);
    Assert.isTrue(list.size()==1, "把数据转换成集合失败了");
}

List arrayToList(Object source)

把一个数组转换成一个集合。

@Test
public void test10(){
    Employee zhangsan    = new Employee("zhangsan");
    Employee[] employees={zhangsan};
    List list = CollectionUtils.arrayToList(employees);
    Assert.isTrue(list.size()==1, "把数据转换成集合失败了");
}

到此这篇关于Springboot内置的工具类之CollectionUtils的文章就介绍到这了,更多相关Springboot内置的工具类内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • springboot实现在工具类(util)中调用注入service层方法

    一.新建BeanUtil类 import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.ApplicationContext; import org.springframework.context.Applic

  • 使用springboot在工具类中读取配置文件(ClassPathResource)

    springboot工具类中读取配置文件 1.创建配置文件(application.properties) spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin spring.activemq.in-memory=true spring.activemq.pool.enabled=false 2.创建工具类(PropertiesUtil.

  • springboot如何读取配置文件到静态工具类

    目录 springboot读取配置文件到静态工具类 我们可以用Environment 来解决 将配置文件的值加载到工具类的静态变量中(多环境运行加载) 首先创建一个SpringBoot项目 创建配置文件 创建实体类 springboot读取配置文件到静态工具类 通常我们读取配置文件可以用@Value注解和@Configuration,@ConfigurationProperties(prefix = "xxx")等注解,但是这种方式是无法把配置读取到静态变量的,如果我们想在项目初始化时

  • springboot实现后台上传图片(工具类)

    本文实例为大家分享了springboot实现后台上传图片的具体代码,供大家参考,具体内容如下 1.先配置启动类 继承WebMvcConfigurer 重写方法 @SpringBootApplication //@MapperScan("com.example.demo.Mapper") public class DemoApplication implements WebMvcConfigurer { public static void main(String[] args) { S

  • Springboot基础之RedisUtils工具类

    SpringBoot整合Redis 引入Redis依赖 <!-- redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 设置Redis的Template RedisConfig.java package cn

  • Springboot内置的工具类之CollectionUtils示例讲解

    前言 实际业务开发中,集合的判断和操作也是经常用到的,Spring也针对集合的判断和操作封装了一些方法,但是最令我惊讶的是,我在梳理这些内容的过程中发现了一些有趣的现象,我的第一反应是不敢相信,再想一想,没错,我是对的.所以强烈建议大家可以认真看完这篇文章,这一篇绝对有价值,因为有趣的是我我竟然发现了Spring的两个bug. org.springframework.util.CollectionUtils 集合的判断 boolean hasUniqueObject(Collection col

  • 分享一个安卓的内置多种工具类的Activity

    一个安卓的Activity,内置了多种工具类.要用的话,让自己的Activity继承这个Activity,各种方便,便于理解我在每个方法上都写了详细的注释,添加了网络部分,添加了表单文件一键上传 演示图 代码 void Call(java.lang.String number) 拨打=电话的方法 void download(java.lang.String url, NetResult result) 用于下载文件的函数 java.lang.String formatMemorySize(lon

  • SpringBoot 内置工具类的使用

    目录 断言 对象.数组.集合 ObjectUtils StringUtils CollectionUtils 文件.资源.IO 流 FileCopyUtils ResourceUtils StreamUtils 反射.AOP ReflectionUtils AopUtils AopContext 断言 断言是一个逻辑判断,用于检查不应该发生的情况 Assert 关键字在 JDK1.4 中引入,可通过 JVM 参数-enableassertions开启 SpringBoot 中提供了 Assert

  • 浅谈springboot内置tomcat和外部独立部署tomcat的区别

    前两天,我去面了个试,面试官问了我个问题,独立部署的tomcat跟springboot内置的tomcat有什么区别,为什么存在要禁掉springboot的tomcat然后将项目部署到独立的tomcat当中? 我就想,不都一个样?独立部署的tomcat可以配置优化?禁AJP,开多线程,开nio?而且springboot内置的tomcat多方便,部署上服务器写个java脚本运行即可.现在考虑下有什么条件能优于内置tomcat的. 1.tomcat的优化配置多线程?内置的也可以配置多线程 server

  • SpringBoot内置tomcat启动原理详解

    前言 不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在springboot是怎么启动的呢? 内置tomcat 开发阶段对我们来说使用内置的tomcat是非常够用了,当然也可以使用jetty. <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-bo

  • 使用SpringBoot内置web服务器

    目录 一.SpringBoot默认web服务器? 二.如何配置当前web容器? 三.内嵌Web服务器如何切换(从tomcat到jetty)? 四.Web容器怎么自动配置? 五.web容器启动源码解析? 六.SpringBoot内置服务器不使用SPI机制特别说明? 本文介绍SpringBoot内置web服务器.知识点有SpringBoot默认web服务器:如何配置当前web容器:内嵌Web服务器如何切换(从tomcat到jetty):Web容器怎么自动配置:web容器启动源码解析:SpringBo

  • springboot内置tomcat之NIO处理流程一览

    目录 前言 tomcat组件 Acceptor组件 Poller 总结 大致流程为 相较于BIO模型的tomcat,NIO的优势分析 前言 springboot内置的tomcat目前默认是基于NIO来实现的,本文介绍下tomcat接受请求的一些组件及组件之间的关联 tomcat组件 本文只介绍NIO中tomcat的组件 我们直接看NIO的核心类NioEndpoint的startInternal方法 Acceptor组件 public void startInternal() throws Exc

  • springboot内置tomcat调优并发线程数解析

    目录 前言 参数 线程池核心线程数 线程池最大线程数 请求最大连接数 accept-count tomcat线程池处理机制 总结 前言 本文解析springboot内置tomcat调优并发线程数的一些参数,并结合源码进行分析 参数 线程池核心线程数 server.tomcat.min-spare-threads:该参数为tomcat处理业务的核心线程数大小,默认值为10 线程池最大线程数 server.tomcat.max-threads:该参数为tomcat处理业务的最大线程数大小,默认值为2

  • SpringBoot内置数据源的持久化与解决方案

    目录 数据层解决方案 与SQL有关的解决方案 SpringBoot提供了3种内嵌的数据源对象供开发者选择 内置持久化解决方案 Springboot内置数据库 数据层解决方案 SQL NoSQL 与SQL有关的解决方案 现有数据层解决方案技术选型 Druid + MyBatis-Plus + MySQL 数据源:DruidDataSource 持久化技术:MyBatis-Plus / MyBatis 数据库:MySQL SpringBoot提供了3种内嵌的数据源对象供开发者选择 HikariCP

  • SpringBoot集成Kafka 配置工具类的详细代码

    目录 1.单播模式,只有一个消费者组 2.广播模式,多个消费者组 spring-kafka 是基于 java版的 kafka client与spring的集成,提供了 KafkaTemplate,封装了各种方法,方便操作,它封装了apache的kafka-client,不需要再导入client依赖 <!-- kafka --> <dependency> <groupId>org.springframework.kafka</groupId> <arti

随机推荐