有文件夹对象列表,我需要将它们连接到绝对路径。每个文件夹都有字段“parentId”(可为空)和“orderNumber”,例如:
class Folder {
folderId;
desc;
parentId;
orderNumber;
}
因此,如果 ParentId == null -> 文件夹是绝对路径中的第一个文件夹,如果不是 -> 我们应该获取父文件夹,依此类推。
我就是这样做的,也许有更简单的方法?
public static void main(String[] args) {
List<Folder> list = new ArrayList<Folder>();
list.add(new Folder(1, null, "root1"));
list.add(new Folder(3, 2, "child2"));
list.add(new Folder(2, 1, "child1"));
list.add(new Folder(5, 4, "child4"));
list.add(new Folder(6, null, "root2"));
list.add(new Folder(4, 3, "child3"));
Integer fromId = 5;
String path = getAbsolutePath(list, getFolderById(list, fromId));
System.out.println(path);
}
public static String getAbsolutePath(List<Folder> list, Folder folder) {
String path = "";
Integer parentId = folder.getParentId();
if (parentId != null) {
Folder parent = getFolderById(list, parentId);
path += getAbsolutePath(list, parent) + "/";
}
path += folder.getDesc();
return path;
}
public static Folder getFolderById(List<Folder> list, Integer folderId) {
return list.stream().filter(row -> row.getId() == folderId).findFirst().get();
}
Output: root1/child1/child2/child3/child4
更新:
public static void main(String[] args) {
List<Folder> list = new ArrayList<Folder>();
list.add(new Folder(1, null, "root1"));
list.add(new Folder(3, 2, "child2"));
list.add(new Folder(2, 1, "child1"));
list.add(new Folder(5, 4, "child4"));
list.add(new Folder(6, null, "root2"));
list.add(new Folder(4, 3, "child3"));
Map<Integer, Folder> folderMap = list.stream().collect(Collectors.toMap(
Folder::getId, folder -> folder
));
Integer fromId = 5;
String path = getAbsolutePath(folderMap, folderMap.get(fromId));
System.out.println(path);
}
DIEA
相关分类