Printer { public static String print(Collection<?> list, String title, int maxLines, Formatter formatter) { if (list == null) { return null; } int max = Math.max(maxLines, MIN_OUTPUT_LINES); int lines = Math.min(list.size(), maxLines); boolean printAll = maxLines == 0 || list.size() <= max; StringBuilder sb = new StringBuilder(lines * EXPECTED_LINE_LENGTH); sb.append(Formatter.NL); if (title != null) { sb.append(title).append(" (").append(list.size()).append(')').append(Formatter.NL); } int c = 0; for (Object e : list) { c++; String value = format(e, formatter); if (printAll || c <= max - 2 || c == list.size()) { sb.append(padNumber(c)).append(". ").append(value); sb.append(Formatter.NL); } else if (c == max - 1) { sb.append(" ..."); sb.append(Formatter.NL); } } return sb.toString(); } private  Printer(); static String print(Collection<?> list, String title, int maxLines, Formatter formatter); static String print(Collection<?> list, String title); static String print(Object[] array, String title); static String repeat(char c, int count);  }
@Test public void testPrint() { List<Integer> list = Arrays.asList(123, 234, 345, 456); String result = Printer.print(list, "Integer list"); String expectedResult = Formatter.NL + "Integer list (4)" + Formatter.NL + " 1. 123" + Formatter.NL + " 2. 234" + Formatter.NL + " 3. 345" + Formatter.NL + " 4. 456" + Formatter.NL; assertEquals(expectedResult, result); }
@Test public void testPrint__maxLines() { List<Integer> list = Arrays.asList(123, 234, 345, 456, 567, 678); Integer[] maxArray = { 2, 3, 4, 7 }; String[] expectedResults = { Formatter.NL + "Integer list (6)" + Formatter.NL + " 1. 123" + Formatter.NL + " ..." + Formatter.NL + " 6. 678" + Formatter.NL, Formatter.NL + "Integer list (6)" + Formatter.NL + " 1. 123" + Formatter.NL + " ..." + Formatter.NL + " 6. 678" + Formatter.NL, Formatter.NL + "Integer list (6)" + Formatter.NL + " 1. 123" + Formatter.NL + " 2. 234" + Formatter.NL + " ..." + Formatter.NL + " 6. 678" + Formatter.NL, Formatter.NL + "Integer list (6)" + Formatter.NL + " 1. 123" + Formatter.NL + " 2. 234" + Formatter.NL + " 3. 345" + Formatter.NL + " 4. 456" + Formatter.NL + " 5. 567" + Formatter.NL + " 6. 678" + Formatter.NL }; for (int i = 0; i < maxArray.length; i++) { int maxLines = maxArray[i]; String expectedResult = expectedResults[i]; String result = Printer.print(list, "Integer list", maxLines, null); assertEquals(expectedResult, result); } }
@Test public void testPrint__null() { List<Integer> list = null; Integer[] array = null; String result1 = Printer.print(list, "Integer list"); String result2 = Printer.print(array, "Integer array"); assertNull(result1); assertNull(result2); }
@Test public void testPrint__noTitle() { Long[] array = {11223344L, 55667788L}; String result = Printer.print(array, null); String expectedResult = Formatter.NL + " 1. 11223344" + Formatter.NL + " 2. 55667788" + Formatter.NL; assertEquals(expectedResult, result); }