使用Java的一些新特性实现些比较繁琐的事情。
一、List去除重复元素
Java8之前,List去重的话,多数都是使用循环比较方式,Java8提供了更简单的方式,一句代码搞定,如下:
List<String> list = Arrays.asList("a", "b", "c", "d", "a", "c", "b");
List<String> distinctList = list.stream().distinct().collect(Collectors.toList());
二、List转换为Set
List转换为Set,其实也包括去重功能啦,代码如下:
List<String> list = Arrays.asList("a", "b", "c", "d", "a", "c", "b");
Set<String> set = list.stream().collect(Collectors.toSet());
三、List转换为数组
// String[] array = (String[]) list.toArray(); 这样子强制转换是会报错的
List<String> list = new ArrayList<>();
String[] array = list.toArray(new String[list.size()]);
以下技巧使用了Apache Commons内的工具
在pom文件里面引入maven配置:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
四、去除Json字符串里面的转义字符
使用json的场景中这种操作比较常见,json字符串中含有转义字符导致序列化失败,这时就需要先去除其中的转义字符。
示例代码:
StringEscapeUtils.unescapeJava(args);
五、List<String>对象示例,转换为数据库查询的in条件
传入字符串aaa,bbb,ccc,现在要将字符串作为查询条件,需要转换为这样:'aaa','bbb','ccc'
示例代码:
String.format("'%s'", StringUtils.join(str.split(","),"','"));