一、数据合并
Object valueObject1[] = new Object[]{"1", "1"};
Object valueObject2[] = new Object[]{"8"};
// 数组添加元素
valueObject2 = ArrayUtils.add(valueObject2, "90");
// 多个数据合并
Object valueObject[] = ArrayUtils.addAll(valueObject1, valueObject2);
二、对象复制
import org.springframework.beans.BeanUtils;
ViewUserDataResponseDTO data = new ViewUserDataResponseDTO();
ViewUserResponseDTO viewUserResponseDTO = userMapper.userToViewUserResponseDTO(user);
BeanUtils.copyProperties(viewUserResponseDTO, data);
三、forEach循环
List<Map> list = new ArrayList<Map>() {{
add(new HashMap(){{
put("id", "01");
put("name", "有效");
}});
add(new HashMap(){{
put("id", "02");
put("name", "无效");
}});
}};
list.forEach(userMap -> {
this.sendTask(item, userMap);
});
四、in Sql封装
StringBuilder sql = new StringBuilder("select detail from s_dict s where KIND_CODE=? ");
String v_codes[] = codes.split(",");
sql.append(" and s.code in(").append(StringUtils.repeat("?,", v_codes.length));
sql = new StringBuilder(sql.substring(0, sql.length() - 1) + ")");
五、String.join,List转为“,”拼装字符串
List<Map> resultList = = new ArrayList<Map>() {{
add(new HashMap(){{
put("id", "01");
put("name", "有效");
}});
add(new HashMap(){{
put("id", "02");
put("name", "无效");
}});
}};
List<String> details = new ArrayList<String>();
resultList.forEach(obj -> {
details.add(MapUtils.getString(obj, "id"));
});
return String.join(",", details);
/* 将对象姓名拼接成String并用分隔符隔开*/
String collect3 = list.stream().map(User::getName).collect(Collectors.joining(","));
六、工具类:CollectionUtils、Collections
import org.springframework.util.CollectionUtils;
import java.util.Collections;
List<Map> resultList = = new ArrayList<Map>() {{
add(new HashMap(){{
put("id", "01");
put("name", "有效");
}});
add(new HashMap(){{
put("id", "02");
put("name", "无效");
}});
}};
if(CollectionUtils.isEmpty(resultList)){
return Collections.emptyList();
} else {
return resultList;
}
七、Lists数组复制
import com.google.common.collect.Lists;
List<Map> resultList = = new ArrayList<Map>() {{
add(new HashMap(){{
put("id", "01");
put("name", "有效");
}});
add(new HashMap(){{
put("id", "02");
put("name", "无效");
}});
}};
List<Map> copys = Lists.newCopyOnWriteArrayList(resultList );
八、数组转List、List转数组
1、数组互转
java.util.Arrays;
// 数组转List
String[] s = {"a","b","c"};
List list = Arrays.asList(s);
// List转数组
List<String> list = new ArrayList<String>() {{
add("01");
add("02");
}};
Object params [] = list.toArray();
2、String[]与List<String>的相互转换
1)String[]转List<String>
String[] arr = new String[]{"s1","s2","s3"};
List<String> list = Arrays.asList(arr);
2)List<String>转String[]
List<String> list = new ArrayList<String>();
list.add("s1");
list.add("s2");
list.add("s3");
String[] arr = list.toArray(new String[list.size()]);
九、jdk1.8
1、构建新的List
List<BusItem> relatedMatters = new ArrayList<>();
List<String> relatedMatterIdList = relatedMatters.stream().map(e ->
e.getBusId()
).collect(Collectors.toList());
List<StaffPublic> result = staff.stream().map(temp -> {
StaffPublic obj = new StaffPublic();
obj.setName(temp.getName());
obj.setAge(temp.getAge());
if ("mkyong".equals(temp.getName())) {
obj.setExtra("this field is for mkyong only!");
}
return obj;
}).collect(Collectors.toList());
List<Staff> staff = Arrays.asList(
new Staff("mkyong", 30, new BigDecimal(10000)),
new Staff("jack", 27, new BigDecimal(20000)),
new Staff("lawrence", 33, new BigDecimal(30000))
);
2、List转Map
1)指定key-value,value是对象中的某个属性值
Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
2)指定key-value,value是对象本身,User->User 是一个返回本身的lambda表达式:
Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
3)指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身:
Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4)指定key-value,value是对象本身,Function.identity()是简洁写法,也是返回对象本身,key 冲突的解决办法,这里选择第二个key覆盖第一个key:
Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
5)分组聚合
List<Map> list = new ArrayList<Map>() {{
add(new HashMap(){{
put("kind_code", "state");
put("id", "01");
put("name", "有效");
}});
add(new HashMap(){{
put("kind_code", "state");
put("id", "02");
put("name", "无效");
}});
}};
Map<String,List<Map>> map0 = CollectionUtils.isEmpty(list)?Maps.newHashMap():(Map<String, List<Map>>) list.stream().collect(Collectors.groupingBy(e -> MapUtils.getString(e, "kind_code")));
Map<String, List<String> map1 = CollectionUtils.isEmpty(list)?Maps.newHashMap():(Map<String, List<String>>) list.stream().collect(Collectors.groupingBy(e -> MapUtils.getString(e, "kind_code"), Collectors.mapping(e1 -> MapUtils.getString(e1, "id"), Collectors.toList())));
3、Filter过滤
List<Person> peoples = Arrays.asList(
new Person("java", 22),
new Person("js", 35),
new Person("css", 31)
);
查找元素
findAny():返回当前流中的任意元素
findFirst():查找第一个元素
Person result3 = peoples.stream()
.filter((p) -> "java".equals(p.getName()) && 22 == p.getAge())
.findAny()
.orElse(null);
System.out.println(result3);
Person result4 = peoples.stream()
.filter((p) -> "java".equals(p.getName()) && 22 == p.getAge())
.findFirst()
.orElse(null);
System.out.println(result4);
// 使用map收集
String name = peoples.stream()
.filter(p -> "js".equals(p.getName()))
.map(Person::getName)
.findAny()
.orElse("");
System.out.println(name);
List<String> names = peoples.stream()
.map(Person::getName)
.collect(Collectors.toList());
names.forEach(System.out::println);
4、排序
/**
* 自然排序 定制排序
*/
emps.stream()
.sorted((e1 ,e2) -> {
if (e1.getAge().equals(e2.getAge())){
return e1.getName().compareTo(e2.getName());
} else{
return e1.getAge().compareTo(e2.getAge());
}
})
.forEach(System.out::println);
5、日期
LocalDate localDate =LocalDate.now();
LocalDate localDate2 = LocalDate.of(2016,12,12);
Period pe = Period.between(localDate, localDate2);
System.out.println(pe);
// 从默认时区的系统时钟获取当前的日期时间。不用考虑时区差
LocalDateTime date = LocalDateTime.now();
// 手动创建一个LocalDateTime实例
LocalDateTime date2 = LocalDateTime.of(2017, 12, 17, 9, 31, 31, 31);
// Duration:计算两个时间之间的间隔
// Period:计算两个日期之间的间隔
Instant ins1 = Instant.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant ins2 = Instant.now();
Duration dura = Duration.between(ins1, ins2);
System.out.println(dura);
System.out.println(dura.toMillis());
LocalTime localTime = LocalTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime localTime2 = LocalTime.now();
Duration du2 = Duration.between(localTime, localTime2);
System.out.println(du2);
System.out.println(du2.toMillis());
// DateTimeFormatter: 格式化时间/日期
// 自定义格式
LocalDateTime ldt = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
String strDate1 = ldt.format(formatter);
String strDate = formatter.format(ldt);
// 解析字符串to时间
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String localTime = df.format(time);
LocalDateTime ldt4 = LocalDateTime.parse("2017-09-28 17:07:05",df);
LocalDate today = LocalDate.now();
// 取本月第1天: 2018-05-01
LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth());
// 取本月第2天:2018-05-02
LocalDate secondDayOfThisMonth = today.withDayOfMonth(2);
// 取本月最后一天,再也不用计算是28,29,30还是31: 2018-05-31
LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth());
// 取下一天:2018-06-01
LocalDate firstDayOf2015 = lastDayOfThisMonth.plusDays(1);
5、数组过滤特性
1)总数量
long count = persons.stream().filter(person -> person.getAge() > 20) .count();
2)最大值、最小值
List<Integer> list = Lists.newArrayList(3, 5, 2, 9, 1);
int maxInt = list.stream().max(Integer::compareTo).get();
int minInt = list.stream().min(Integer::compareTo).get();
/* 判断是否所有对象年龄超过20岁 */
boolean b = list.stream().allMatch(x -> x.getAge() > 20);
System.out.println("判断是否所有对象年龄超过20岁:" + b);
/* 返回年龄最大的对象 */
User user = list.stream().max((e1, e2) -> e1.getAge().compareTo(e2.getAge())).get();
System.out.println("返回年龄最大的对象" +user);
十、uuid
import org.hibernate.id.UUIDGenerator;
String id = UUIDGenerator.generateUUID();
十一、获取文件名称或后缀
String fileName="GoogleChrome.zip";
String name = fileName.substring(0, fileName.lastIndexOf("."));
String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
System.out.println("name: " + name);
System.out.println("suffix: " + suffix);
十二、字典枚举类
package com.zwjp.common.enums;
/**
* 字典数据
*/
public enum DictEnum {
/**
* 发布状态
*/
MODEL_PUBLISH_STATUS_1("1", "发布审核", "MODEL_PUBLISH_STATUS", "发布状态"),
MODEL_PUBLISH_STATUS_2("2", "发布中", "MODEL_PUBLISH_STATUS", "发布状态"),
;
private String code;
private String detail;
private String type;
private String typeDetail;
private DictEnum(String code, String detail, String type, String typeDetail) {
this.code = code;
this.detail = detail;
this.type = type;
this.typeDetail = typeDetail;
}
public static DictEnum getByCode(String type, String code) {
for (DictEnum orgOperateEnum : values()) {
if (orgOperateEnum.getType().equals(type) && orgOperateEnum.getCode().equals(code)) {
return orgOperateEnum;
}
}
return null;
}
public static String getDetailByCode(String type, String code) {
String detail = null;
DictEnum obj = getByCode(type, code);
if (obj != null) {
detail = obj.getDetail();
}
return detail;
}
public String getCode() {
return this.code;
}
public String getDetail() {
return this.detail;
}
public String getType() {
return type;
}
public String getTypeDetail() {
return typeDetail;
}
}
十三、日志打印
long start = System.currentTimeMillis();
ServerResponse<Page<Map<String, Object>>> serverResponse = this.getWaitSynExecData();
long end = System.currentTimeMillis();
log.info(this.getAppCommissionEnum().getName() + "待办查询耗时: {}ms", end - start);
十四、Jdk1.8 stream
1、获取Map中的某个KEY,返回List<String>
List<Map<String, Object>> dataList = Lists.newArrayList();
List<String> idList = dataList.stream()
.filter((p) -> StringUtils.isNotBlank(MapUtils.getString(p, "id")))
.map(e -> MapUtils.getString(e, "id")).collect(Collectors.toList());
2、List<Map>转Map,返回Map
List<Map<String, Object>> dataList = Lists.newArrayList();
Map<String, String> mapData = dataList .stream()
.collect(Collectors.toMap(e -> MapUtils.getString(e, "id"), e -> MapUtils.getString(e, "name")));
3、相同KEY对应的值合并,返回合并后的List<Map>
List<Map<String, Object>> dataList = Lists.newArrayList();
List<Map> newDataList = dataList.stream()
// 表示id为key, 接着如果有重复的,那么从BillsNums对象o1与o2中筛选出一个,这里选择o1,
// 并把id重复,需要将nums和sums与o1进行合并的o2, 赋值给o1,最后返回o1
.collect(Collectors.toMap(ek -> MapUtils.getString(ek,"pmid"), a -> a
, (o1,o2)-> {
o1.put("sl",MapUtils.getInteger(o1,"sl",0)+MapUtils.getInteger(o2,"sl",0));
return o1;
})).values().stream().collect(Collectors.toList());
4、转int数组
List<Integer> argTypeList= Lists.newArrayList();
int[] argTypes = argTypeList.stream().map(e -> Types.VARCHAR).mapToInt(Integer::valueOf).toArray();
十五、树封装
package cn.tree;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.MapUtils;
import org.assertj.core.util.Lists;
import org.springframework.util.CollectionUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @deprecated 树封装(通过java 递归循环实现树封装)
* @author alhs
*/
@Data
public class TreeTest {
/**
* 封装树对象
* @param treeVals
* @return
*/
public List<TreeNode> getTree(String treeVals){
List<Map> list = Lists.newArrayList();
List<String> vtreeVals = Arrays.asList(treeVals.split(","));
// List<Map>转为List<TreeNode>
List<TreeNode> trees = (List<TreeNode>)list.stream().map(e -> new TreeNode(MapUtils.getString(e,"id"),MapUtils.getString(e,"name"),MapUtils.getString(e,"parent_id"),null)).collect(Collectors.toList());
// 获取所有根节点
List<TreeNode> rootTrees = getRootTree(vtreeVals,trees);
// 递归处理时限树封装
recursionTreeNode(rootTrees,trees);
return rootTrees;
}
/**
* 获取树的所有第一层根节点(对象)
* @param treeVals
* @param trees
* @return
*/
private List<TreeNode> getRootTree(List<String> treeVals, List<TreeNode> trees){
List<TreeNode> rootTrees = trees.stream().filter(e -> treeVals.contains(e.getId())).map(e -> {
e.setParentId(null); // 父节点置空
return e;
}).collect(Collectors.toList());
return rootTrees;
}
/**
* 封装多个根节点树
* @param rootTrees
* @param trees
*/
private void recursionTreeNode(List<TreeNode> rootTrees, List<TreeNode> trees) {
for (TreeNode dataTree : rootTrees) {
recursionTreeNode(dataTree, trees);
if (!CollectionUtils.isEmpty(dataTree.getChildren())) {
recursionTreeNode(dataTree.getChildren(), trees);
}
}
}
/**
* 封装单个根节点树
* @param rootTree
* @param trees
*/
private void recursionTreeNode(TreeNode rootTree, List<TreeNode> trees) {
if (!CollectionUtils.isEmpty(trees)) {
List<TreeNode> children = trees.stream().filter(e -> rootTree.getId().equals(e.getParentId())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(children)) {
rootTree.setChildren(children);
trees.removeAll(children);
}
}
}
/**
* @deprecated 定义树Bean
* @author alhs
* @date 2020-12-21
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
class TreeNode {
private String id;
private String name;
private String parentId;
private List<TreeNode> children;
}
}
package cn.tree;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.MapUtils;
import org.assertj.core.util.Lists;
import org.springframework.util.CollectionUtils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author alhs
* @deprecated 树封装(通过java 递归循环实现树封装)
*/
@Data
public class TreeTest {
/**
* 封装树Id
*
* @param treeVals
* @return
*/
private List<String> getTreeIds(String treeVals) {
List<Map> list = Lists.newArrayList();
List<String> vtreeVals = Arrays.asList(treeVals.split(","));
// List<Map>转为List<TreeNode>
List<TreeNode> trees = (List<TreeNode>) list.stream().map(e -> new TreeNode(MapUtils.getString(e, "id"), MapUtils.getString(e, "name"), MapUtils.getString(e, "parent_id"), null)).collect(Collectors.toList());
// 获取根节点
List<String> ids = this.getRootTreeIds(vtreeVals, trees);
if (!CollectionUtils.isEmpty(ids)) {
// 递归处理时限树封装
this.recursionTreeNodeIds(ids, trees);
} else {
ids = Lists.newArrayList();
}
return ids;
}
/**
* 获取树的所有第一层根节点
*
* @param treeVals
* @param trees
* @return
*/
private List<String> getRootTreeIds(List<String> treeVals, List<TreeNode> trees) {
List<TreeNode> rootTrees = trees.stream().filter(e -> treeVals.contains(e.getId())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(rootTrees)) {
List<String> ids = (List<String>) rootTrees.stream().map(e -> e.getId()).collect(Collectors.toList());
trees.removeAll(rootTrees);
return ids;
} else {
return Lists.newArrayList();
}
}
/**
* 封装多个根节点树
*
* @param treeIds
* @param trees
*/
private void recursionTreeNodeIds(List<String> treeIds, List<TreeNode> trees) {
List<TreeNode> nodeTrees = trees.stream().filter(e -> treeIds.contains(e.getId())).collect(Collectors.toList());
if (!CollectionUtils.isEmpty(nodeTrees)) {
List<String> ids = (List<String>) nodeTrees.stream().map(e -> e.getId()).collect(Collectors.toList());
trees.removeAll(nodeTrees);
treeIds.addAll(ids);
recursionTreeNodeIds(treeIds, trees);
}
}
/**
* @author alhs
* @date 2020-12-21
* @deprecated 定义树Bean
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
class TreeNode {
private String id;
private String name;
private String parentId;
private List<TreeNode> children;
}
}
十六、lombok常用注释
package cn.tree;
// import lombok.AllArgsConstructor;
// import lombok.Data;
// import lombok.NoArgsConstructor;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
/**
* @author alhs
* @date 2020-12-21
* @deprecated 定义树Bean
*/
// 通常 @Data 会加在一个值可以被更新的对象上,像是日常使用的 DTO 们、或是 JPA 裡的 Entity 们,就很适合加上 @Data 注解,适合用在 POJO 或 DTO 上
@Data // 整合包,只要加了 @Data 这个注解,等于同时加了以下注解: @Getter/@Setter/@ToString/@EqualsAndHashCode/@RequiredArgsConstructor
// 适合加在值不希望被改变的类上,像是某个类的值当创建后就不希望被更改,只希望我们读它而已
//@Value // 整合包,只要加了 @Value 这个注解,但是他会把所有的变量都设成 final 的,其他的就跟 @Data 一样,等于同时加了以下注解: @Getter/@ToString/@EqualsAndHashCode/@RequiredArgsConstructor
@Getter // 生成 get
@Setter // 生成 set
@NoArgsConstructor // 生成一个没有参数的构造器
@AllArgsConstructor // 生成一个包含所有参数的构造器
@ToString // 自动重写 toString() 方法
@EqualsAndHashCode // 自动生成 equals(Object other) 和 hashcode() 方法,包括所有非静态变量和非 transient 的变量
@RequiredArgsConstructor // 生成一个包含 "特定参数" 的构造器,特定参数指的是那些有加上 final 修饰词的变量
@Slf4j // 日志框架的变种注解
public class TreeNode {
private String id;
private String name;
private String parentId;
private List<TreeNode> children;
}
常用:
@Data
@NoArgsConstructor // 生成一个没有参数的构造器
@AllArgsConstructor // 生成一个包含所有参数的构造器
@ToString // 自动重写 toString() 方法
@EqualsAndHashCode // 自动生成 equals(Object other) 和 hashcode() 方法,包括所有非静态变量和非 transient 的变量