1、java8的时间运用,真的很好用,强力推荐,其对时间的计算,比如想知道当前时间的前多少天,每月最后一天,对时间的加减等运算,非常方便。但目前使用过程中(到目前为止),时间如果后端用LocalDate/LocaDateTime 接收 eg:private LocalDate contractEndTime可能会遇到有些不兼容的情况,能用,比如拷贝会不是很方便或与其他版本兼容问题)。
// 说明:均为示例片段
**java8的时间格式化**
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter olddtf = DateTimeFormatter.ofPattern("yyyy-MM");
LocalDateTime dts = LocalDateTime.parse(“2020-03-04 23:59:59”, dtf);
*获取当前时间*
LocalDate ld = LocalDate.now();
*当前时间减去1天(昨天)*
ld = ld.minusDays(1);
*格式化时间变成String*
String endDate = ld.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
*上个月第一天*
String lastMonthOfFirstDay = ld.minusMonths(1).with(TemporalAdjusters.firstDayOfMonth())
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
2、java8对集合进行取交集,并集,差集,去重等等非常方便实用。
// 只是示例片段
*取差集(lastMonthProjectList比thisMonthProjectList大的差集,谁在前面表示谁减),Set同理*
List<String> xList = lastMonthProjectList.stream().filter(i -> !thisMonthProjectList.contains(i))
.collect(Collectors.toList());
*取交集*
List<String> rList = bl.stream().filter(i -> xList.contains(i)).collect(Collectors.toList());
list.addAll(rList);
*通过distinct去重*
List<String> list = list.stream().distinct().collect(Collectors.toList());
*对集合进行map(重新组装)操作*
List<Node> ll = list.stream().map(nf -> {
String nodeId = nf.getNodeId();
Org org = orgRestful.getOrgById(nodeId);
Node node = org2Node(org);
return node;
}).collect(toList());
*通过filter对集合进行过滤操作(很常规操作)*
List<CcpVirtualTreeOperateLogs> ll = ll.stream().filter(log -> log.getParentFullId().contains(parentId)).collect(toList());
*java8 的函数(Function)运用---java8的4大函数之一*
Node node = this.fetchNode(log.getNodeId(), f -> org2Node(this.orgRestful.getOrgById(f)));
private Node fetchNode(String id, Function<String, Node> function) {
return function.apply(id);
}
*组装集合数据到map中*
Map<String, String> resourceMap = resourceList.stream()
.collect(Collectors.toMap(Resource::getResourceId, Resource::getName));
*根据集合对象某字段进行去重,然后获取新的该集合*
List<NcCfgImportExcelForm> distinctList = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(NcCfgImportExcelForm::getAccountId))),
ArrayList::new));
*通过groupingBy进行分组去重*
int s = list.stream().collect((Collectors.groupingBy(NcCfgImportExcelForm::getProjectId))).size();
if (s != 1) {
throw new BaseException("每次导入只能是一个项目,即项目id应该全部相同");
}