Java使用
目录
你平时写代码形成了哪些规范
- 命名习惯
管理前缀使用:“get”,“list”,“page”,“save”,“mod”,“del”
验证参数正确性用“verify”,执行业务逻辑用“do”,重组数据用“handle”
导入数据用“import”,导出数据用“export”
如何删除list中不符合条件的数据
userList.removeIf(user -> user.getStatus()!=2);
如何初始化list大小,并在指定位置设值
List<User> userList = new ArrayList<>(Collections.nCopies(count,null));
userList.set(index, user);
如何求list中某属性的和
int scores = userList.stream().mapToInt(User::getScore).sum();
如何取某list对象中某个属性的集合
List<Long> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());
如何将List对象中的数据按某一属性分组
Map<Integer,List<User>> userMap = userList.stream().collect(Collectors.groupingBy(User::getAge));
如何将list转化成map
Map<Long, User> usermap = userList.stream().collect(Collectors.toMap(User::getId, user -> user));
//如果key重复,则抛异常:Java.lang.IllegalStateException:Duplicate key。选择第二个key覆盖第一个key
Map<Long, User> usermap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2 ));
异步执行任务要如何处理
CompletableFuture.runAsync(() -> {
System.out.println("Hello world");
});
CompletableFuture.allOf(
CompletableFuture.runAsync(() -> {System.out.println("Hello world1");}),
CompletableFuture.runAsync(() -> {System.out.println("Hello world2");})
).join();
import lombok.extern.slf4j.Slf4j;
CountDownLatch countDownLatch = new CountDownLatch(list.size());
list.forEach(item->{
CompletableFuture.runAsync(() -> {
try {
} finally {
countDownLatch.countDown();
}
});
});
try {
countDownLatch.await();
} catch (InterruptedException e) {
log.error(e.getMessage(),e);
}
导入Excel举例
//使用SpringBoot + hutool
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelReader;
public void importUser(@ApiParam("导入excel文件") MultipartFile file) throws IOException{
if (ObjectUtil.isEmpty(file)) {}
// 文件类型校验
String type = FileTypeUtil.getType(file.getInputStream());
String originalFilename = file.getOriginalFilename();
// 文件大小校验
if (file.getSize() > 1024 * 1024 * 10) {
log.error("/manage/saleOperatorTarget/importSaleOperatorTarget 上传失败: 文件大小超过10M,文件大小为:{}", file.getSize());
}
// 数据验证
ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
reader.addHeaderAlias("姓名", "name");
List<User> importList = reader.readAll(User.class);
}
导出Excel举例
//使用SpringBoot + hutool
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.core.io.IoUtil;
@Resource
private HttpServletResponse response;
private void doExportUser(List<User> rows) throws IOException {
ExcelWriter writer = ExcelUtil.getWriter(true);
writer.addHeaderAlias("name", "姓名");
writer.setOnlyAlias(true);
writer.write(rows, true);
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename=user.xlsx");
ServletOutputStream out=response.getOutputStream();
writer.flush(out, true);
writer.close();
IoUtil.close(out);
}
如何设置不使用科学计数法表示数据
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.format(doubleNum);
BigDecimal的四舍五入怎么处理
new BigDecimal(1).divide(new BigDecimal(3),2, BigDecimal.ROUND_HALF_UP);
// 以下写法不可取,因会出Non-terminating decimal expansion; no exact representable decimal result.
//new BigDecimal(1).divide(new BigDecimal(3)).setScale(2, BigDecimal.ROUND_HALF_UP);
LocalDateTime & LocalDate & Date的转化
//Date转LocalDateTime
LocalDateTime.ofInstant(Calendar.getInstance().getTime().toInstant(),
ZoneId.systemDefault());
//Date转LocalDate
LocalDateTime.ofInstant(Calendar.getInstance().getTime().toInstant(),
ZoneId.systemDefault())
.toLocalDate();
//LocalDate转Date
Date.from(LocalDate.now()
.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant()
);
//LocalDateTime转Date
Date.from(LocalDateTime.now()
.atZone(ZoneId.systemDefault())
.toInstant()
);

浙公网安备 33010602011771号