Java SE 7ã§å°å ¥ãããNIO2ã®Filesã¯ã©ã¹ã§readAllLinesã¡ã½ããã使ã£ã¦å¤§ããªãã¡ã¤ã«ãèªãã¨ããã¼ãã¡ã¢ãªãå§è¿«ã¾ãã¯OutOfMemoryErrorãèµ·ããã¾ãã
List<String> lines = Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8);
Windows 7 64bitï¼12GBã¡ã¢ãªï¼ã§ãJava SE 8 64bitçä¸ã§ãã¼ãã¡ã¢ãªãµã¤ãºã®ãªãã·ã§ã³ãæå®ããã«ï¼ããã©ã«ãï¼å®è¡ãã8GBã®ãã¡ã¤ã«ãä¸è¿°ã³ã¼ãã§èªã¿è¾¼ã¾ããã¨ããOutOfMemoryErrorãçºçãã¾ããã
Java SE 8ã§å°å ¥ãããStream APIã使ã£ã¦å¤§ããªãã¡ã¤ã«ãèªã¿è¾¼ãã¨ã©ãã試ãã¦ã¿ã¾ããã
try (BufferedReader reader = Files.newBufferedReader(Paths.get(args[0]), Charset.forName("UTF-8"))) { reader.lines() .map(s -> s.split(" ")[0]) .distinct() .sorted() .forEach(System.out::println); } catch (IOException e) { throw new UncheckedIOException(e); }
8GBã®ãã¡ã¤ã«ãèªã¿è¾¼ã¿ã¾ããããã¼ãã¡ã¢ãªä½¿ç¨éã¯æ°åMBãã300MBãå¢æ¸ãã¤ã¤å¦çãçµãã¾ããã
ãªãã»ã©ãé 延ããããã¨ã®ã¡ãªããã1ã¤è¦ãã¾ããã