我正在上課
public class Entity {
private String id;
private List<Entity> children;
// getters, constructor, etc.
}
現在我需要將此 Entity 類資料轉換為 Map<String, Entity>
我的方法接受(串列物體)作為輸入并且需要轉換為 Map
我試過像:
public static Map<String, Entity> group(List<Entity> entities) {
Map<String, Entity> map = new HashMap<>();
for (Entity e : entities) {
if (!map.containsKey(e.getId())) {
map.put(e.getId(), ??? e.getChildren() ???); // my point of confusion
}
}
return map;
}
我的問題是,當我需要通過getChildren(). 如何實作它以獲得正確的資料?
樣本資料格式如下。
[
{
id: bos
childs:[
{
id: manager1
childs: [{id: worker11}, {id: worker12}]
},
{
id: manager2
childs: [{id: worker21}, {id: worker22}]
}
]
}
]
uj5u.com熱心網友回復:
基本上,您有一個脫節的物體圖。
因此,您需要實作一個圖遍歷演算法,以便將 Entities 的資料放入生成的 Map。
用于此類目的的最簡單演算法之一是深度優先搜索。
該演算法背后的核心思想:
- 維護一個堆疊,其中包含正在檢查的元素。
- 搜索從被壓入堆疊頂的根元素開始。
- 元素被反復從堆疊頂移除。如果下一個元素有尚未見過的子元素,它們將被推入堆疊頂部。
以下是迭代實作的樣子:
public static Map<String, Entity> group(List<Entity> entities) {
Map<String, Entity> result = new HashMap<>();
Set<String> seen = new HashSet<>();
for (Entity e : entities) {
if (seen.add(e.getId())) { // entity was not previously encountered
addAllChildren(result, seen, e);
}
}
return result;
}
/**
* Depth first search algorithm implementation
*/
public static void addAllChildren(Map<String, Entity> result,
Set<String> seen,
Entity root) {
Deque<Entity> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
Entity current = stack.pop();
result.put(current.getId(), current);
for (Entity child: current.getChildren()) {
if (seen.add(child.getId())) {
stack.push(child);
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520463.html
標籤:爪哇列表算法哈希图
