 <p>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:</p> <pre><code>private static Collection&lt;String&gt; extractBases(String[] nodes) { Arrays.sort(nodes); // optional, to ensure order Deque&lt;String&gt; bases = new ArrayDeque&lt;&gt;(); bases.addFirst(nodes[0]); for (int i = 1; i &lt; nodes.length; i++) { if (!nodes[i].contains(bases.peekFirst())) { // if it's not a child bases.addFirst(nodes[i]); } } return bases; } </code></pre> <p>You can check a demo with your input here: <a href="http://ideone.com/sjEfvc" rel="nofollow">http://ideone.com/sjEfvc</a></p>