yiwei
yiwei

Reputation: 4190

How do I extract the base URI?

I have a bunch of URIs (Strings) like this:

METRICS.COMPANY.APP1
METRICS.COMPANY.APP1.TOTAL.90DAY
METRICS.COMPANY.APP1.TOTAL.WEEKLY
METRICS.COMPANY.APP1.TOTAL.MONTHLY
METRICS.COMPANY.APP2
METRICS.COMPANY.APP2.TOTAL.90DAY
METRICS.COMPANY.APP2.TOTAL.WEEKLY
METRICS.COMPANY.APP2.TOTAL.MONTHLY
METRICS.BUSINESS.DECISIONS
METRICS.BUSINESS.DECISIONS.MONTHLY
METRICS.BUSINESS.DECISIONS.ANNUALLY
METRICS.EMPLOYEE
METRICS.EMPLOYEE.WEEKLY

Is there a way I can extract the unique "base" URI from each set of similar URIs? That is, I am interested in only getting:

METRICS.COMPANY.APP1
METRICS.COMPANY.APP2
METRICS.BUSINESS.DECISIONS
METRICS.EMPLOYEE

Upvotes: 1

Views: 99

Answers (1)

Fred Porciúncula
Fred Porciúncula

Reputation: 8902

Assuming your data will be ordered, like it is in your example, thus assuming the base will always appear before its children, this is what I came up with:

private static Collection<String> extractBases(String[] nodes) {
    Arrays.sort(nodes); // optional, to ensure order

    Deque<String> bases = new ArrayDeque<>();
    bases.addFirst(nodes[0]);

    for (int i = 1; i < nodes.length; i++) {
        if (!nodes[i].contains(bases.peekFirst())) { // if it's not a child
            bases.addFirst(nodes[i]);
        }
    }

    return bases;
}

You can check a demo with your input here: http://ideone.com/sjEfvc

Upvotes: 2

Related Questions