我有一個文本文件,其中分層數據在文本文件中的平面結構中可用。Java - 從文本文件中的平面結構讀取分層數據並構建散列圖
child parent
Y, X
Z, Y
A, Z
它像X是Y的父親,它本身Z和Z的父親是A的父親。它可以以任何順序出現在文件中。我需要構建一個hashmap,其中鍵應該是元素,值應該是所有祖先元素的列表。例如,HashMap應該具有基於上述數據的條目,如下所示:其中A = [Z,Y,X],Y = [X],Z = [Y,X]。
我已經在java中編寫了一個代碼來構建這個hashmap。只需要知道是否有更有效的方法來做到這一點。 邏輯是
- 閱讀其中的孩子是關鍵,家長是價值
從上面創建遞歸遍歷每個孩子和父母建立的名單HashMap中的散列映射整個文件。
public class Test { public static final String FILE_NAME = "dataset1"; public static final HashMap<String,String> inputMap = new HashMap<String,String>(); public static final Map<String, ArrayList<String>> parentChildMap = new HashMap<String,ArrayList<String>>(); private static void readTextFile(String aFileName) throws IOException { Path path = Paths.get(aFileName); try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)){ String line = null; while ((line = reader.readLine()) != null) { String[] dataArray = line.split(","); String child = dataArray[0]; String parent = dataArray[1]; inputMap.put(child, parent); } } } public static ArrayList<String> getParents(String childId, ArrayList<String> parents) { if (childId == null) return parents; String parentId = inputMap.get(childId); if(parentId!=null) parents.add(parentId); getParents(parentId, parents); return parents; } public static void main(String[] s) throws IOException { readTextFile(FILE_NAME); for(String child : inputMap.keySet()) { ArrayList<String> parents = getParents(child, new ArrayList<String>()); parentChildMap.put(child, parents); } }
Cana孩子有多個家長? – AJC
不,但父母可以有自己的父母和孩子需要他們所有人 – KBR