Aggregation of cartesian product of two hierachical trees using Java

為{幸葍}努か 提交于 2019-12-12 01:55:20

问题


Need to do aggregation of Cartesian product of two hierarchical tree structures using Java, Please suggest some good methods or API to do this.

Tree Structure:

Country Tree :

Node|Id|ParentId

World|1|1
Asia|2|1
Europe|3|1
India|4|2
China|5|2
UK|6|3
Hungary|7|3
Cyprus|8|3

Profit Tree:

Node|Id|ParentId
Profit|1|1
Revenue|2|1
Expense|3|1

Cartesian product of these two products would give me 24 combinations (8 X 3). I need to aggregate values for each of the combination.

For example, I want to know Total revenue of Europe, Asia and World, Total Profit of Europe etc


回答1:


It's a bit hard to answer without details of the structures. But I'll guess what they might be and you can extrapolate to your structures.

enum EconomicDataType {
    PROFIT, REVENUE, EXPENSE;
}

interface GeographicNode {
    int getEconomicData(EconomicDataType type);
}

class Region implements GeographicNode {
    private List<GeographicNode> geographiesInRegion;
    public int getEconomicData(EconomicDataType type) {
        return geographiesInRegion.stream()
            .mapToInt(geog -> geog.getEconomicData(type))
            .sum();
    }
}

class Country implements GeographicNode {
    private EnumMap<GeographicNode, Integer> economicData;
    public int getEconomicData(EconomicDataType type) {
        return economicData.get(type);
    }
}

I have modelled economic data as a map rather than a tree because, frankly, it makes no sense to me to make it a hierarchy given there's nothing hierarchical about the data.

I also haven't handled the situation in which data is missing. Not hard to add with a containsKey check before getting the data from the map.

Retrieving someing like total revenue for europe is:

europe.getEconomicData(EconomicDataType.REVENUE);

Simple :-)



来源:https://stackoverflow.com/questions/27893810/aggregation-of-cartesian-product-of-two-hierachical-trees-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!