SortLogFile { public static void sortLogFile(InputStream logFile, PrintWriter sortedFile) throws IOException { Collection<LogFileParser.LogEntry> sorted = new TreeSet<>((entry1, entry2) -> { String stamp1 = entry1.getTimestamp(); String stamp2 = entry2.getTimestamp(); if (stamp1.equals(stamp2)) { if (entry1.getContents().equals(entry2.getContents())) { return Integer.compare(entry1.hashCode(), entry2.hashCode()); } return entry1.getContents().compareTo(entry2.getContents()); } return stamp1.compareTo(stamp2); }); BufferedReader br = new BufferedReader(new InputStreamReader(logFile)); LogFileParser parser = new LogFileParser(null, br); while (parser.hasMoreEntries()) { sorted.add(parser.getNextEntry()); } for (LogFileParser.LogEntry entry : sorted) { entry.writeTo(sortedFile); } }  static void sortLogFile(InputStream logFile, PrintWriter sortedFile); static void main(String... args);  }
@Test public void testRandomLog() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(baos), true); LogWriter logWriter = new RandomLogWriter(printWriter); for (int i = 0; i < 100; i++) { logWriter.info(String.valueOf(i)); } printWriter.flush(); printWriter.close(); byte[] bytes = baos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); StringWriter stringWriter = new StringWriter(); printWriter = new PrintWriter(stringWriter, true); SortLogFile.sortLogFile(bais, printWriter); String sorted = stringWriter.toString(); BufferedReader reader = new BufferedReader(new StringReader(sorted)); LogFileParser parser = new LogFileParser(null, reader); String prevTimestamp = null; while (parser.hasMoreEntries()) { LogFileParser.LogEntry entry = parser.getNextEntry(); String timestamp = entry.getTimestamp(); if (prevTimestamp != null) { assertThat(prevTimestamp.compareTo(timestamp)) .as("Prev: " + prevTimestamp + ", current: " + timestamp) .isLessThanOrEqualTo(0); } prevTimestamp = entry.getTimestamp(); } }