分享一个树级结构数据,自动生成各个层次节点的code代码方法,优势在于可以在获取到子级的同时,可以直接根据code获取出它对应的所有父级的对应code,避免循环递归全扫描
public class OrgCodeHierarchy { private static final int MAX_SEQUENCE = 999; private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static Map<String, Boolean> existingOrgCodeMaps = new HashMap<>(); public static Map<String, Boolean> convertListToMap(List<String> orgCodes) { Map<String, Boolean> orgCodeMap = new HashMap<>(); for (String code : orgCodes) { orgCodeMap.put(code, true); } return orgCodeMap; } public static String generateChildOrgCode(String parentOrgCode, List<String> existingOrgCodes) { existingOrgCodeMaps=convertListToMap(existingOrgCodes); if (parentOrgCode == null || parentOrgCode.isEmpty()) { return generateNewOrgCode(); } char startChar = parentOrgCode.charAt(0); int level = parentOrgCode.length() / 4; char nextChar = startChar; String childOrgCode = parentOrgCode + nextChar + String.format("%03d", 1); while (existingOrgCodes.contains(childOrgCode)) { childOrgCode = generateNextAvailableOrgCode(childOrgCode); } return childOrgCode; } private static String generateNextAvailableOrgCode(String orgCode) { int sequenceNumber = Integer.parseInt(orgCode.substring(orgCode.length() - 3)) + 1; return orgCode.substring(0, orgCode.length() - 3) + String.format("%03d", sequenceNumber); } public static List<String> generateChildOrgCodes(String parentOrgCode, List<String> existingOrgCodes, int numChildren) { List<String> childOrgCodes = new ArrayList<>(); for (int i = 1; i <= numChildren; i++) { String childOrgCode = generateChildOrgCode(parentOrgCode, existingOrgCodes); childOrgCodes.add(childOrgCode); existingOrgCodes.add(childOrgCode); } return childOrgCodes; } private static String generateNewOrgCode() { String newOrgCode = "A001"; while (existingOrgCodeMaps.containsKey(newOrgCode)) { int sequenceNumber = Integer.parseInt(newOrgCode.substring(1)) + 1; if (sequenceNumber > MAX_SEQUENCE) { newOrgCode = getNextChar(newOrgCode.charAt(0)) + "001"; } else { newOrgCode = newOrgCode.charAt(0) + String.format("%03d", sequenceNumber); } } existingOrgCodeMaps.put(newOrgCode, true); return newOrgCode; } private static char getNextChar(char currentChar) { int index = ALPHABET.indexOf(currentChar); if (index == ALPHABET.length() - 1) { return 'A'; } else { return ALPHABET.charAt(index + 1); } } public static void main(String[] args) { String parentOrgCode = null; List<String> existingOrgCodes = new ArrayList<>(); existingOrgCodes.add("A001"); existingOrgCodes.add("A001A001"); List<String> childOrgCodes = generateChildOrgCodes(parentOrgCode, existingOrgCodes, 3); System.out.println("Generated child org codes:"); for (String orgCode : childOrgCodes) { System.out.println(orgCode); } } }
互相交流,我觉得应该还有更好的方法,但是需求催的急,暂时就做到这里吧
岁月无声无息的溜走,除了带走一个无聊者的时光,还会沉淀一个努力者的人生。