1.集合Map
HashMap:hashCode
TreeMap:默认按key升序排序,可以自定义排序
LinkedHashMap:保留了记录的插入顺序,即put的顺序
//map中,通过key获取value,匹配key可以忽略大小写
String value = map.get("OrgType".equalsIgnoreCase("OrgType"));
//getOrDefault(key, default)方法:如果存在key,则返回其对应的value,否则返回给定的默认值
if(!areaMap.containsKey(areaName)){bd = BigDecimal.ZERO;}else {bd = areaMap.get(areaName);}
等于
bd = areaMap.getOrDefault(areaName, BigDecimal.ZERO);
boolean containsKey(Object key)
//返回map集合中所有Key和所有Value,遍历Key和Value
Set set = map.keySet();
Collection values = map.values();
//key
for(String key : map.keySet()){
System.out.println(key);
}
//value
for(BigDecimal value : map.values()){
System.out.println(value);
}
循环遍历:
Set> entriesSet = map.entrySet();
在for循环中使用entries实现Map的遍历(最常见)
for(Map.Entry entry : entriesSet ){
String mapKey = entry.getKey();
BigDecimal mapValue = entry.getValue();
}
通过Iterator遍历:
Iterator> entries = entriesSet.iterator();
while(entries.hasNext()){
Entry entry = entries.next();
String key = entry.getKey();
BigDecimal value = entry.getValue();
}
java8的stream遍历:
map.forEach((k,v)->{
});
2.集合List和Set
ArrayList是保留add顺序的
//按照集合的对象元素的某个属性(比如日期)降序
private void listSortDate(List list){
Collections.sort(list, new Comparator() {
@Override
public int compare(BranchNameDto o1, BranchNameDto o2) {
if(o2 == null) return -1;
if(o1 == null) return 1;
return o2.getShowTime().compareTo(o1.getShowTime());
}
});
}
//移除元素最好不要直接用remove
for(StatisticsDto statisticsDto : statisticsDtoList){
String name = statisticsDto.getName();
if("测试".equals(name)) statisticsDto.setCount(count);
if("开发".equals(name)) statisticsDtoList.remove(statisticsDto);
}
改成
List removeList = new ArrayList<>();
for(StatisticsDto statisticsDto : statisticsDtoList){
String name = statisticsDto.getName();
if("测试".equals(name)) statisticsDto.setCount(count);
if("开发".equals(name)) removeList.add(statisticsDto);
}
statisticsDtoList.removeAll(removeList);
List list = Arrays.asList("", "")
不可以对该list进行add、remove操作,可以改成:
List list = new ArrayList<>(Arrays.asList("", ""))
List list = new ArrayList() {{add(12);add(20);}}
list1:1 2 3 list2:3 4 5
//并集 123345
list1.addAll(list2);
//交集 3
list1.retainAll(list2);
//差集 12
list1.removeAll(list2);
//无重复并集 12345
list2.removeAll(list1); 45
list1.addAll(list2);
3.集合、数组之间的转换
int[] 转List:
int[] arrays = new int[]{1,2};
List list = Arrays.stream(arrays).boxed().collect(Collectors.toList()); //java8写法
数组元素只能是基本数据类型而不能为对象类型
数组初始化:
int[] array = new int[3]; //定义长度3
int[] array = new int[]{1,2,3};
int[] array = {1,2,3}
"1,2" 用,隔开的字符串转为list
String[] str = string.split(",");
List<String> list1 = Arrays.asList(string.split(","));
项目里有工具类 strToIntegerList(),底层也是用split(",")
List<Integer> list2 =StringUtil.strToIntegerList(string);
前端传递:"[1,2]",json数组的字符串
List list = JSONArray.parseArray(jsonString, Integer.class);
将List集合转化为用符号隔开的String字符串 ["小红","小花"]---->"小红,小花"
String string = Joiner.on(",").join(list);
list转数组
List list;
String[] array = new String[list.size()];
list.toArray(array);
遇到一个bug:
List list= Arrays.asList(1,2);
dtoList.forEach(item->{
list.remove(item.getNodeLevel());
});
这样会报错,用Arrays转换的集合list,里面的元素类型是:Arrays$ArrayList(Arrays.asList的返回值类型)
改:
List list= new ArrayList<>();
list.add(1);
list里面的元素类型是:ArrayList
或者
List list = new ArrayList<>(Arrays.asList(deficiencyData.split(",")));
可以指定集合哪个位置插入
list.add(0, entity);
不能用list.set(0,entity)
可以截取集合其中几个,需返回即需接收
List subList = list.subList(0,10)
4.集合归类
//审批按钮归类处理
private List auditButtonHandle(List buttonList){
List auditButtonList = new ArrayList<>(); //各角色名称+对应按钮集合的 集合
List oneRoleButtonList = new ArrayList<>(); //一个角色的按钮集合
for (PolicyNodeButton old : buttonList) {
boolean flag = true; //给整合后集合添加子元素标志,true:添加,false:不添加,其年龄相加
for (PolicyDemandRecordDto newClassify : auditButtonList) {
if (newClassify.getRoleShowName(). equals(old.getRoleShowName())) {//判断姓名是否相同
oneRoleButtonList = newClassify.getButtonList();
oneRoleButtonList.add(old);
flag = false;
}
}
if (flag) {
PolicyDemandRecordDto dto = new PolicyDemandRecordDto();
dto.setRoleShowName(old.getRoleShowName());
oneRoleButtonList.add(old);
dto.setButtonList(oneRoleButtonList);
auditButtonList.add(dto);//给整合后集合添加子元素
}
}
return auditButtonList;
}
5.集合for循环
for循环里最好不要一条条查询,把查询条件一起放在Set中查询
然后查询结果分组:一个年龄值,对应一个集合
List<SysUser> list = this.userMapper.findByAges(ageSet);
Map<Integer, List<SysUser>> map = list.stream().collect(Collectors.groupingBy(SysUser::getAge));
for (UserEntity userEntity : list) {
Integer age = userEntity.getAge();
if (map.containsKey(age)) {
map.get(age).add(userEntity);
} else {
List ageList = new ArrayList<>();
ageList.add(userEntity);
map.put(age, ageList);
}
}
6.Collections集合
Collections的sort方法默认是升序排列,如果需要降序排列时就需要重写compare方法
对List中某个key的日期值降序
对List集合中的对象进行按某个属性排序
7.分批次操作
//分批更新:500条数据一个批次处理
private void updateBatch(List<ResultDto> updateList){
int batchSize = 500;
// 计算需要多少批次来处理所有数据
int totalDataSize = updateList.size();
int totalBatches = (int) Math.ceil((double) totalDataSize / batchSize);
int i=1;
for (int batchNumber = 0; batchNumber < totalBatches; batchNumber++) {
int startIndex = batchNumber * batchSize;
int endIndex = Math.min(startIndex + batchSize, totalDataSize);
List<ElectricParkResultDto> batchData = updateList.subList(startIndex, endIndex);
// 处理批次数据
if(CollectionUtils.isNotEmpty(batchData)){
logger.info("更新 第【{}】个批次处理,处理数={}", i, batchData.size());
resultMapper.updateBatch(batchData);
}
i++;
}
}
8.集合中添加对象需注意
public static void main(String[] args){
List insertList = new ArrayList<>();
EntDocument document = new EntDocument();
document.setEntName("测试");
document.setFileName("aaa");
insertList.add(document);
//如果用同一个对象,则insertList里面两个元素编号是一样的,并且文件名都是bbb
document.setFileName("bbb");
insertList.add(document);
//这样写,就可以实现了,insertList两个元素编号是不一样的
EntDocument documentImg = new EntDocument();
BeanUtils.copyProperties(document, documentImg);
documentImg.setFileName("bbb");
insertList.add(documentImg);
}
就像我们循环插入一样的道理,
for (Ent ent : entList) {
EntDocument document = new EntDocument(); //新建一个对象,插入
document.setEntName(ent.getEntName());
document.setFileName(ent.getFileName());
insertList.add(document);
}
每次set的都是同一个对象的属性,然后又将这个对象add进集合,
最终集合里面存放的n个变量都是指向堆中的同一个对象,这个对象的属性就是你最后一次set的属性。
所以在每次循环的时候,你需要在堆中重新创建一个对象用来set属性。而不是每次重复set同一个对象
9.对象
对象和list一样是会存储的
setXxx(sysUser);
private void setXxx(HttpServletRequest request, SysUser sysUser){
String ip = IpUtil.getIP(request);
int port = request.getRemotePort();
sysUser.setIp(ip);
sysUser.setPort(port);
}
10.对象集合赋值给另一个对象集合
当对另一个对象集合修改时,原对象集合也会对应修改;都是相同的地址;;一个对象被add加入集合中,如果这个对象属性值修改后,则集合中该对象对应的数据值也会修改
public static void main(String[] args){
List list = new ArrayList<>();
StatisticsDto dto = new StatisticsDto();
dto.setName("哈哈");
list.add(dto);
List list2 = new ArrayList<>();
//list2.addAll(list); 这样写或者用copy,则对list2修改,list也会对应修改;需要下面这样写,重新new一个对象然后一个个赋值放入list2 注意:List等基本类型集合是不会改变的
for(StatisticsDto dto1 : list){
StatisticsDto dto2 = new StatisticsDto();
BeanUtils.copyProperties(dto1, dto2);
list2.add(dto2);
}
for(StatisticsDto dto1 : list2){
dto1.setName("呵呵");
}
System.out.println(list.get(0).getName());
System.out.println(list2.get(0).getName());
}
stream的filter方法,两个对象集合是不会有联动的
List dataList=xxxMapper.findXxx(userRole.getRoleId(),Arrays.asList(1,2));
List dataMenuList=dataList.stream().filter(item->(item.getType()!=4)).collect(Collectors.toList());

11.类对象的属性拷贝
BeanUtils.copyProperties(source, target, CommonUtil.getNullPropertyNames(source));
对于属性名相同,类型不同,会尝试转换
最后一个参数:忽视的属性:
自写的方法CommonUtil:获取所有字段值为null的属性名
CommonUtil.getNullPropertyNames(source)
用于BeanUtils.copyProperties()拷贝属性时,忽略空值
12.不可变类,方法中调用其他方法
集合、对象、Stringbuilder会变,字符串、BigDecimal不会变
public static void main(String[] args){
BigDecimal bigDecimal = BigDecimal.ZERO;
//bigDecimal = BigDecimal.valueOf(100); //这样写,是输出100
aa(bigDecimal); //这样写,是输出0;集合、对象、Stringbuilder会变,字符串、BigDecimal不会变
System.out.println(bigDecimal);
}
private static void aa(BigDecimal bigDecimal){
bigDecimal = BigDecimal.valueOf(200);
}
//这样写才可以
public static void main(String[] args){
BigDecimal bigDecimal = BigDecimal.ZERO;
Map map = aa(bigDecimal);
bigDecimal = map.get("bigDecimal");
System.out.println(bigDecimal);
}
private static Map aa(BigDecimal bigDecimal){
Map map = new HashMap<>();
bigDecimal = BigDecimal.valueOf(200);
map.put("bigDecimal", bigDecimal);
return map;
}
13.JSON、JSONObject、JSONArray
//json对象格式的字符串
String jsonString = "{\"id\":116,\"mobile\":\"1115\",\"realName\":\"张三\"}";
//json对象格式的字符串 --> json对象
JSONObject jsonObj = JSONObject.parseObject(jsonString);
//json对象格式的字符串 --> 实体类对象
SysUser sysUser1 = JSON.parseObject(jsonString, SysUser.class);
SysUser sysUser2 = JSONObject.parseObject(jsonString, SysUser.class);
//实体类对象 --> json对象格式的字符串
String jsonString2 = JSON.toJSONString(sysUser1);
String jsonString1 = JSONObject.toJSONString(sysUser1);
//json数组格式的字符串
String jsonArrayString = "[{"name": "张三", "age": 25},{"name": "李四", "age": 30}]";
//json数组格式的字符串 --> 集合 "[{},{}]"
List<SysUser> list = JSONArray.parseArray(jsonArrayString, SysUser.class);
List<SysUser> list = JSONArray.parseArray(jsonArrayString, SysUser.class);
//对象 --> Map
Map map = JSON.parseObject(JSON.toJSONString(sysUserEntity), Map.class);
//Map --> 实体类即对象
SysUserEntity sysUserEntity = JSON.parseObject(JSON.toJSONString(map), SysUserEntity.class);
// String <--> List<String>
List attachmentFileCodesList = JSON.parseArray(attachmentFileCodes);
String attachmentFileCodes = JSON.toJSONString(attachmentFileCodesList);
"10","20" 以,隔开的字符串 --> List<String>
List<Integer> idList = Arrays.asList(nameStr);
10,20 以,隔开的字符串 --> List<Integer>
List<Integer> idList = StringUtil.strToIntegerList(idStr); //strToIntegerList自写的工具类
14.String和StringBuilder
String.format("%s (%s)", , )
如果直接展示%则用%%
15.Integer
int类型这样直接判断,如果是null值会报错
if(xxxDto.getType() != 3)
改成
if(xxxDto.getType() != null && xxxDto.getType() != 3)
16.BigDecimal
初始化:整数的随便,有小数的double,用第二种方法
BigDecimal bd1 = new BigDecimal(100);
BigDecimal bd2 = BigDecimal.valueOf(100.2); //String、Integer都有valueOf()
Object obj;
Integer integer = Integer.parseInt(obj.toString()); //(Integer)obj 不能这样强转型
Bigdecimal转Integer:
bigdecimal.intValue();
BigDecimal四舍五入:
bd1.setScale(2, BigDecimal.ROUND_HALF_UP); //直接把值四舍五入
bd1.divide(bd2, 2, BigDecimal.ROUND_HALF_UP); //相除,结果保留2位小数,四舍五入
如果是10.2,则最后得值是10.20,会自动补0位;
对于负数:-10.258,则-10.26
Integer四舍五入:
BigDecimal bd = new BigDecimal((float)thisCount/lastCount); //整数型运算,结果会去除小数点后的部分,转成float类型,可以保留小数
Double d = bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
数据库:decimal(10,2),DEFAULT '0.00'
总共能存10位数字,末尾2位是小数,字段最大值99999999.99
数据库:int(11) 21亿
不论是int(3)还是int(11),它在数据库里面存储的都是4个字节的长度,在使用int(3)的时候如果你输入的是10,
会默认给你存储位010,也就是说这个3代表的是默认的一个长度,当你不足3位时,会帮你不全
加:add();减:subtract;乘:multiply;除:divide 可以保留小数
()里的参数不能为空
必须有返回值
BigDecimal bd2 = bd1.add(new BigDecimal(100));
17.Switch
//状态1和2,都是返回"测试"
switch (status) {
case 1 :
case 2 : return "测试";
}
匹配到时:
从当前的case语句块开始执行,执行完剩余的case语句块;
如果有return、break语句块,则跳出switch
没有匹配到时:
执行default语句
也可以没有default语句
18.@Value
@Value("${app.secret}")
不能用于static和controller
19.日期时间
Calendar calendar = Calendar.getInstance(); //日历
Integer thisYear = calendar.get(Calendar.YEAR); //获取今年的
Integer thisMonth = calendar.get(Calendar.MONTH) + 1; //或者当前月份
Integer lastYear = todayYear - 1; //去年的
calendar.setTime(new Date());
calendar.add(Calendar.DATE, +90);
String threeMonthsAfterDate = sf.format(calendar.getTime()); //90天后的日期
Date类型的日期比较:
before()和after(),只适用年月日,而且不包含=
或
java.util.Date类实现了Comparable接口
int compareTo = date1.compareTo(date2)
mapper.xml中的sql:
DATE_FORMAT(publish_time, '%Y-%m-%d') BETWEEN #{startTime} AND #{endTime}
数据库中:
date 年月日
datetime 年月日 时分秒
timestamp 年月日 时分秒,该字段类型可以设置自动更新时间值
yyyyMMdd格式的获取年份:
Date date = DateUtils.getFormatDate("20180404", "yyyyMMdd");
System.out.println(DateUtils.formatDateToString(date, "yyyy"));
返回日期格式设置:
返回:2022-02-21 T02:07:23.000+00:00
spring:
jackson:
date-format: yyyy-MM-dd HH:mm:ss
joda-date-time-format: yyyy-MM-dd HH:mm:ss
time-zone: GMT+8
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone="GMT+8")
private DATA xxx;
这样前端可以传递string的,然后返回也正确
如果还不行,再加个:
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
常用积累1&spm=1001.2101.3001.5002&articleId=140170414&d=1&t=3&u=f8faaa6e30a1402ab9f0d7faa33800f7)
112

被折叠的 条评论
为什么被折叠?



