如何提取基URI?

时间:2015-08-18 00:01:46

标签: java

我有一堆URI(Strings),如下所示:

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

有没有办法可以从每组相似的URI中提取唯一的“基础”URI?也就是说,我只对以下内容感兴趣:

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

1 个答案:

答案 0 :(得分:2)

假设您的数据将按照您的示例进行排序,因此假设基数将始终显示在其子项之前,这就是我想出的:

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;
}

您可以在此处查看带有输入的演示:http://ideone.com/sjEfvc