我正在尝试找到一种使用表中当前数据结构创建资产管理报告的方法:
Company_Name Company_id Managing_Company_id
Target 002 150
Coles 003 150
Wesfarmers 150 100
Shell 001 150
Max Company X 100 null
Woolworths Group 250 100
Caltex 201 250
Woolworths 202 250
Aldi 300 null
PGX 650 600
然后报告会将其迭代到层次结构中
Max Company X
Wesfarmers
Target
Coles
Shell
Woolworths Group
Caltex
Woolworths
Aldi
PGX
有一个可以让我管理此结构的Collection吗?
答案 0 :(得分:1)
乍一看,我在考虑topological sort
,它带有一个图/树来处理您的情况,但是在实现解决方案时。我认为没有必要只使用 double 映射来记录关系来解决问题:
id
和name
之间的关系; managing
和managed
之间的关系; 然后我们可以有一个解决方案:
public static void main(String args[]) {
List<List<String>> listList = prepareTestData();
Map<String, String> idNameMap = new HashMap<>();
Map<String, String> managingRelationMap = new HashMap<>();
List<String> theTop = new ArrayList<>();
for (List<String> list : listList) {
idNameMap.put(list.get(1), list.get(0));
if (list.get(2) == null || list.get(2).equals(list.get(1))) { // no managing or managed by itself;
theTop.add(list.get(1));
} else {
managingRelationMap.put(list.get(1), list.get(2));
}
}
// add specials whose managing does not exist;
for (String s : managingRelationMap.keySet()) {
if (!idNameMap.containsKey(managingRelationMap.get(s))) {
theTop.add(s);
}
}
for (String top : theTop) {
printManagingStructure(top, managingRelationMap, idNameMap, 1);
}
}
private static List<List<String>> prepareTestData() {
List<List<String>> listList = new ArrayList<>();
listList.add(new ArrayList<>(Arrays.asList("Target", "002", "150")));
listList.add(new ArrayList<>(Arrays.asList("Coles", "003", "150")));
listList.add(new ArrayList<>(Arrays.asList("Wesfarmers", "150", "100")));
listList.add(new ArrayList<>(Arrays.asList("Shell", "001", "150")));
listList.add(new ArrayList<>(Arrays.asList("Max Company X", "100", null)));
listList.add(new ArrayList<>(Arrays.asList("Woolworths Group", "250", "100")));
listList.add(new ArrayList<>(Arrays.asList("Caltex", "201", "250")));
listList.add(new ArrayList<>(Arrays.asList("Woolworths", "202", "250")));
listList.add(new ArrayList<>(Arrays.asList("Aldi", "300", null)));
listList.add(new ArrayList<>(Arrays.asList("PGX", "650", "600")));
return listList;
}
private static void printManagingStructure(String managingId, Map<String, String> managingRelationMap,
Map<String, String> idNameMap, int gapCount) {
System.out.println(String.format("%" + gapCount * 20 + "s%-20s", "", idNameMap.get(managingId)));
if (!managingRelationMap.containsValue(managingId)) {
return;
}
managingRelationMap.entrySet().stream().filter(entry -> entry.getValue().equals(managingId))
.forEach(entry -> {
printManagingStructure(entry.getKey(), managingRelationMap, idNameMap, gapCount + 1);
});
}
输出将是:
Max Company X
Wesfarmers
Shell
Target
Coles
Woolworths Group
Caltex
Woolworths
Aldi
PGX
答案 1 :(得分:0)
有关使用适当数据结构的问题是主观的。即使使用当前的数据结构,也不难获得所需的信息。您也可以选择List
中的Tree
。另一方面,您可以轻松地旋转自己的数据结构,例如。自定义tree
,每个根节点存储在HashMap
中。就是说,Java没有提供存储这种特殊情况的直接方法。如果数据量很大,则应考虑使用某种基于图形的数据库。