List<String> (List<String> srcLines, int requiredLineNumber) { if (srcLines.size() < 2 || srcLines.size() <= requiredLineNumber) { return srcLines; } List<String> res = new LinkedList<>(srcLines); // first join lines with a single { or } for (int i = res.size()-1; i > 0 ; i--) { String s = res.get(i); if (s.trim().equals("{") || s.trim().equals("}")) { res.set(i-1, res.get(i-1).concat(s)); res.remove(i); } if (res.size() <= requiredLineNumber) { return res; } } // now join empty lines for (int i = res.size()-1; i > 0 ; i--) { String s = res.get(i); if (s.trim().isEmpty()) { res.set(i-1, res.get(i-1).concat(s)); res.remove(i); } if (res.size() <= requiredLineNumber) { return res; } } return res; }