user3222372
user3222372

Reputation: 382

Aggregation of cartesian product of two hierachical trees using Java

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

Upvotes: 1

Views: 319

Answers (1)

sprinter
sprinter

Reputation: 27986

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 :-)

Upvotes: 1

Related Questions