Java常用代码记录
约 1586 字大约 5 分钟
2025-04-02
按ID分组找出最早的那个
public static void main(String[] args) throws InterruptedException {
ArrayList<CoSaasCustomerRelated> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
CoSaasCustomerRelated coSaasCustomerRelated = new CoSaasCustomerRelated();
coSaasCustomerRelated.setExternalId("客户"+i);
coSaasCustomerRelated.setAddTime(LocalDateTime.now());
Thread.sleep(500L);
list.add(coSaasCustomerRelated);
}
for (int i = 0; i < 3; i++) {
CoSaasCustomerRelated coSaasCustomerRelated = new CoSaasCustomerRelated();
coSaasCustomerRelated.setExternalId("客户"+i);
coSaasCustomerRelated.setAddTime(LocalDateTime.now());
Thread.sleep(500L);
list.add(coSaasCustomerRelated);
}
System.out.println(JSON.toJSONString(list));
Map<String, LocalDateTime> firstTimeMap = new HashMap<>();
for (CoSaasCustomerRelated related : list) {
String externalId = related.getExternalId();
LocalDateTime addTime = related.getAddTime();
if (addTime != null) {
firstTimeMap.merge(externalId, addTime, (oldVal, newVal) -> newVal.isBefore(oldVal) ? newVal : oldVal);
}
}
System.out.println(JSON.toJSONString(firstTimeMap));
}找出两个集合不同的部分
public static void main(String[] args) {
HashSet<Integer> newSet = Sets.newHashSet(1, 2, 3, 4, 5);
HashSet<Integer> oldSet = Sets.newHashSet(1, 2, 3, 4, 6);
Set<Integer> onlyInNewSet = new HashSet<>(newSet);
onlyInNewSet.removeAll(oldSet);
Set<Integer> onlyInOldSet = new HashSet<>(oldSet);
onlyInOldSet.removeAll(newSet);
Set<Integer> intersection = new HashSet<>(newSet);
intersection.retainAll(oldSet);
System.out.println(newSet);
System.out.println(oldSet);
System.out.println("onlyInNewSet"+onlyInNewSet);
System.out.println("onlyInOldSet"+onlyInOldSet);
System.out.println("intersection"+intersection);
}都为空,或都不为空校验
{
boolean anyBlank = StringUtils.isAnyBlank(appletId, appletImage, appletPath, appletTitle);
boolean allBlank = StringUtils.isAllBlank(appletId, appletImage, appletPath, appletTitle);
//有任意为空 并且不是都为空
if (anyBlank && !allBlank) {
log.info("createMaterial-创建小程序参数不全=【{}】", JSON.toJSONString(req));
throw new CommonException("小程序参数必须全为空或全非空");
}
}根据当前时间确定统计开始和结束时间
import lombok.Data;
import lombok.Getter;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* <p>同步范围</p>
* @author bx
*/
@Data
public class SyncRange {
/**
* yyyy-MM-dd
*/
private String startDate;
/**
* yyyy-MM-dd
*/
private String endDate;
/**
* 员工id
*/
private List<String> userIds;
/**
* 部门id
*/
private List<Long> deptIds;
public LocalDateTime getStartDate() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
if (StringUtils.hasText(startDate)) {
return LocalDateTime.of(LocalDate.parse(startDate, formatter), LocalTime.MIN);
} else {
LocalDateTime now = LocalDateTime.now();
return now.plusDays(-3).with(LocalTime.MIN);
}
}
public LocalDateTime getEndDate() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
if (StringUtils.hasText(endDate)) {
return LocalDateTime.of(LocalDate.parse(endDate, formatter), LocalTime.MAX);
} else {
return LocalDateTime.now().with(LocalTime.MAX);
}
}
}
// 使用
public static void main(String[] args) {
Set<String> rangeUserIds;
LocalDateTime startDate = null;
LocalDateTime endDate = null;
if (ObjectUtils.isEmpty(range)) {
//不传参数 默认查所有员工,近3天的数据
rangeUserIds = userOpenApi.getRangeUserId(null, null);
LocalDateTime now = LocalDateTime.now();
startDate = now.plusDays(-3).with(LocalTime.MIN);
endDate = now.with(LocalTime.MAX);
} else {
rangeUserIds = userOpenApi.getRangeUserId(range.getUserIds(), range.getDeptIds());
startDate = range.getStartDate();
endDate = range.getEndDate();
}
}根据当前时间确定统计时间集合
/**
*
* 返回时间日期:[2025-03-01, 2025-03-02, 2025-03-03, 2025-03-04]
*/
public static void main(String[] args) {
SyncRangeDTO syncRange = new SyncRangeDTO();
syncRange.setStartDate("2025-03-01");
syncRange.setEndDate("2025-03-04");
//[2025-03-01, 2025-03-02, 2025-03-03, 2025-03-04]
System.out.println(getTrackDate(syncRange));
}
/**
* {
* "startDate": "startDate_2435cbe2468b",
* "endDate": "endDate_4016aa4551ed"
* }
*/
private static List<LocalDate> getTrackDate(DateRangeDTO rangeDTO) {
List<LocalDate> dateList = new ArrayList<>();
if (ObjectUtils.isEmpty(rangeDTO)) {
dateList.add(getLocalDate());
} else {
String beginDateStr = rangeDTO.getStartDate();
String endDateStr = rangeDTO.getEndDate();
if (StringUtils.hasText(beginDateStr) && StringUtils.hasText(endDateStr)) {
LocalDate beginDate = DateUtils.parseLocalDateTime(DateUtils.YYYY_MM_DD, beginDateStr);
LocalDate endDate = DateUtils.parseLocalDateTime(DateUtils.YYYY_MM_DD, endDateStr);
long daysBetween = ChronoUnit.DAYS.between(beginDate, endDate);
for (int i = 0; i <= daysBetween; i++) {
dateList.add(beginDate.plusDays(i));
}
} else {
dateList.add(getLocalDate());
}
}
return dateList;
}
private static LocalDate getLocalDate() {
// from 0 to 23
int hour = LocalDateTime.now().getHour();
LocalDate trackDate;
if (hour <= 21) {
// 昨天
trackDate = LocalDate.now().plusDays(-1);
} else {
// 当天
trackDate = LocalDate.now();
}
return trackDate;
}构建父子层级
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import lombok.Data;
import org.springframework.util.ObjectUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 部门树
*
* @author bx
*/
@Data
public class DepartmentTree {
private Department department;
private List<DepartmentTree> departmentChild;
@Data
public static class Department {
private Long id;
/**
* 租户id
*/
private String tenantId;
/**
* ws部门id
*/
private Long deptId;
/**
* ws父部门id
*/
private Long parentDeptId;
/********** A10 **********
* 组织机构id
*/
private Long ouId;
/**
* 组织(部门)名称
*/
private String name;
/**
* 父节点ID
*/
private Long parentId;
}
public static void main(String[] args) {
String a1 = "{\"id\":1,\"tenantId\":\"tenantId_8559d9b35b43\",\"deptId\":1,\"parentDeptId\":0," +
"\"ouId\":1,\"name\":\"name_850f6d36e8b1\",\"rootId\":0,\"parentId\":0}";
String a2 = "{\"id\":2,\"tenantId\":\"tenantId_8559d9b35b43\",\"deptId\":2,\"parentDeptId\":0," +
"\"ouId\":2,\"name\":\"name_850f6d36e8b1\",\"rootId\":0,\"parentId\":0}";
String a3 = "{\"id\":3,\"tenantId\":\"tenantId_8559d9b35b43\",\"deptId\":3,\"parentDeptId\":0," +
"\"ouId\":3,\"name\":\"name_850f6d36e8b1\",\"rootId\":0,\"parentId\":0}";
String a4 = "{\"id\":4,\"tenantId\":\"tenantId_8559d9b35b43\",\"deptId\":4,\"parentDeptId\":2," +
"\"ouId\":4,\"name\":\"name_850f6d36e8b1\",\"rootId\":0,\"parentId\":2}";
String a5 = "{\"id\":5,\"tenantId\":\"tenantId_8559d9b35b43\",\"deptId\":5,\"parentDeptId\":3," +
"\"ouId\":5,\"name\":\"name_850f6d36e8b1\",\"rootId\":0,\"parentId\":3}";
String a6 = "{\"id\":6,\"tenantId\":\"tenantId_8559d9b35b43\",\"deptId\":6,\"parentDeptId\":4," +
"\"ouId\":6,\"name\":\"name_850f6d36e8b1\",\"rootId\":0,\"parentId\":4}";
ArrayList<Department> list = Lists.newArrayList(
JSON.parseObject(a1, Department.class),
JSON.parseObject(a5, Department.class),
JSON.parseObject(a6, Department.class),
JSON.parseObject(a4, Department.class),
JSON.parseObject(a3, Department.class),
JSON.parseObject(a2, Department.class)
);
List<DepartmentTree> departmentTrees = buildTree(list);
System.out.println(JSON.toJSONString(departmentTrees));
}
public static List<DepartmentTree> buildTree(List<Department> list) {
Map<Long, DepartmentTree> nodeMap = new HashMap<>();
// 将所有节点转成tree对象
for (Department entity : list) {
DepartmentTree tree = new DepartmentTree();
tree.setDepartment(entity);
nodeMap.put(entity.getDeptId(), tree);
}
List<DepartmentTree> rootNodes = new ArrayList<>();
// 循环所有数据
for (Department entity : list) {
//处理当前数据,此时list为空
DepartmentTree currentNode = nodeMap.get(entity.getId());
//找到父id
Long parentId = entity.getParentId();
//找到根部门
if (ObjectUtils.isEmpty(parentId) || !nodeMap.containsKey(parentId)) {
//如果元素父id不在所有元素中,则表明是根部门,dept_id=1, name=深圳微盛网络科技, parent_id=0,只有公司的父接口是0;
rootNodes.add(currentNode);
} else {
//能在所有元素中找到父节点,将子节点存到父节点下
DepartmentTree parentNode = nodeMap.get(parentId);
if (parentNode.getDepartmentChild() == null) {
//如果现在子容器为空则创建个容器
parentNode.setDepartmentChild(new ArrayList<>());
}
//然后将当前元素添加到父节点的子节点目录下
parentNode.getDepartmentChild().add(currentNode);
}
//下一次循环
}
return rootNodes;
}
}除法:返回百分数
public static String calculatePercent(Integer up, Integer down) {
try {
if (up.equals(0) || down.equals(0)) {
return "0%";
}
// 四舍五入
BigDecimal bigDecimal = new BigDecimal(up).divide(new BigDecimal(down), 5, RoundingMode.HALF_UP)
.multiply(BigDecimal.valueOf(100));
//保留2位小数
BigDecimal precent = bigDecimal.setScale(2, RoundingMode.HALF_UP);
return precent+"%";
} catch (Exception e) {
log.error("计算分数失败,now=【{}】,before=【{}】", up, down, e);
}
return "0%";
}迭代版本(推荐)
private void deptCreateIterative(List<DepartmentTree> departmentTrees, Set<Long> createdDeptSet) {
if (CollectionUtils.isEmpty(departmentTrees)) {
return;
}
Queue<DepartmentTree> queue = new LinkedList<>(departmentTrees);
while (!queue.isEmpty()) {
DepartmentTree tree = queue.poll();
SysDepartmentEntity dept = tree.getDept();
// 空值保护
if (ObjectUtils.isEmpty(dept)) {
continue;
}
Long ouId = dept.getOuId();
// 已创建则跳过
if (createdDeptSet.contains(ouId)) {
log.info("部门【{}】已创建,ouId=【{}】,跳过", dept.getName(), ouId);
continue;
}
// 创建并保存部门
try {
boolean success = createAndSaveDept(dept);
if (success) {
createdDeptSet.add(ouId);
} else {
log.warn("部门【{}】创建失败,ouId=【{}】", dept.getName(), ouId);
continue;
}
} catch (Exception e) {
log.error("创建部门失败:{}", dept.getName(), e);
continue;
}
// 将子节点加入队列继续处理
List<DepartmentTree> childNodes = tree.getDeptChild();
if (!CollectionUtils.isEmpty(childNodes)) {
queue.addAll(childNodes);
}
}
}
private Boolean createAndSaveDept(SysDepartmentEntity entity) {
return true;
}递归版本(不推荐)
//构建部门树:根-下级-下下级
public static void main(String[] args) {
List<DepartmentTree> departmentTrees = DeptTreeAssembler.buildTree(addDeptSet);
Set<Long> createdDeptSet = Collections.synchronizedSet(new HashSet<>());
deptCreateRecursion(departmentTrees, createdDeptSet);
}
private void deptCreateRecursion(List<DepartmentTree> departmentTrees, Set<Long> createdDeptSet) {
if (CollectionUtils.isEmpty(departmentTrees)) {
return;
}
for (DepartmentTree tree : departmentTrees) {
SysDepartmentEntity dept = tree.getDept();
if (ObjectUtils.isEmpty(dept)) {
continue;
}
Long ouId = dept.getOuId();
if (createdDeptSet.contains(ouId)) {
log.info("部门已创建,跳过。dept=【{}】", JSON.toJSONString(dept));
continue;
}
try {
boolean success = createAndSaveDept(tree.getDept());
if (success) {
createdDeptSet.add(ouId);
}
} catch (Exception e) {
log.error("创建部门失败:{}, 继续创建下一个", tree.getDept(), e);
continue; // 或者中断整个流程
}
deptCreateRecursion(tree.getDeptChild(), createdDeptSet);
}
}
private Boolean createAndSaveDept(SysDepartmentEntity entity) {
Long parentId = entity.getParentId();
if (parentId == 0) {
//创建根部门
Integer deptIdNew = deptOpenApi.deptCreate(entity.getName(), 0);
if (ObjectUtils.isEmpty(deptIdNew)) {
log.warn("syncDepartment-创建根部门失败,部门名称=【{}】,父部门Id=【{}】", entity.getName(), parentId);
return false;
} else {
entity.setDeptId(Long.valueOf(deptIdNew));
entity.setParentDeptId(0L);
}
} else {
//创建非根部门,上级部门始终早于下级部门创建
SysDepartmentEntity parentEntity = sysDeptUserRepository.queryDeptByOuId(entity.getParentId());
if (ObjectUtils.isEmpty(parentEntity)) {
log.warn("syncDepartment-找不到上级部门,部门名称=【{}】,父OUID=【{}】", entity.getName(), parentId);
return false;
}
Integer deptIdNew = deptOpenApi.deptCreate(entity.getName(), Math.toIntExact(parentEntity.getParentDeptId()));
if (ObjectUtils.isEmpty(deptIdNew)) {
log.warn("syncDepartment-创建部门失败,部门名称=【{}】,父部门Id=【{}】", entity.getName(), parentId);
return false;
} else {
entity.setDeptId(Long.valueOf(deptIdNew));
entity.setParentDeptId(parentEntity.getDeptId());
}
}
boolean result = sysDeptUserRepository.saveDept(entity);
log.info("syncDepartment-创建部门结果=【{}】,部门名称=【{}】,父部门Id=【{}】", result, entity.getName(), parentId);
return result;
}