static String moveImportsUp2(String s) { List l = toLines(s); Pattern p = Pattern.compile("^\\s*import\\s"); // Count import statements on top int iStart = 0; while (iStart < l(l) && p.matcher(l.get(iStart)).find()) ++iStart; // Find import statements in rest L l2 = subList(l, iStart); new L x; ListIterator i = l2.listIterator(); while (i.hasNext()) { S line = i.next(); if (p.matcher(line).find()) { x.add(line); i.remove(); } } // Return null or changed version if (isEmpty(x)) ret null; return fromLines(concatLists(subList(l, 0, iStart), x, l2)); }