Comparator () { return new Comparator() { @Override public int compare(Object o1, Object o2) { String s1 = SorterUtil.getStringPresentation(o1); String s2 = SorterUtil.getStringPresentation(o2); if (isTagPresentation(s1, "head") && isTagPresentation(s2, "body")) return -1; if (isTagPresentation(s1, "body") && isTagPresentation(s2, "head")) return 1; return s1.compareToIgnoreCase(s2); } private static boolean isTagPresentation(final String presentation, final String tagName) { // "head", "head#id", "head.cls" final String lowerCased = StringUtil.toLowerCase(presentation); return lowerCased.startsWith(tagName) && (lowerCased.length() == tagName.length() || !Character.isLetter(lowerCased.charAt(tagName.length()))); } }; }