java8 新機能

2014年3月18日「Java8」正式リリース

Lambda(exam1)

Arrays.sort(array, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return a.compareToIgnoreCase(b);
    }
});
Arrays.sort(array, (a, b) -> a.compareToIgnoreCase(b));


Lambda(exam2)

button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        // do something 1
        // do something 2
    }
});
button.addActionListener(event -> {
    // do something 1
    // do something 2
});


Lambda(exam3)

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        // do something
    }
});
Thread t = new Thread(() -> {
    // do something
});


Lambda(exam4)

public class Logger {
    public void log(Level level, Supplier<String> msg) {
        if (isLoggable(level)) {
            write(level, msg.get());
        }
    }
};

logger.log(Level.INFO, () -> "log message: " + someTimeConsumigMethod()); 
// e -> System.out.println(e)
button.addActionListener(System.out::println);

// (a, b) -> a.compareToIgnoreCase(b)
Arrays.sort(array, String::compareToIgnoreCase);

// x -> new Person(x)
names.stream().map(Person::new);


Stream

List<String> list = Arrays.asList("C", "C++", "Java", "Scala", "Ruby");

int count = 0;
for (String elem : list) {
    if (elem.startsWith("C")) {
        count += elem.length();
    }
}
long count = list.stream()
                 .filter(s -> s.startsWith("C"))
                 .mapToInt(s -> s.length())
                 .sum();
String[] words = Stream.of("C", "C++", "Java", "Scala", "Ruby")
                       .map(s -> s.toUpperCase())
                       .sorted()
                       .toArray(String[]::new);
IntSummaryStatistics stats = IntStream.generate(() -> (int)(Math.random() * 100))
                                      .filter(n -> n >= 80)
                                      .distinct()
                                      .limit(3)
                                      .summaryStatistics();
List<String> fizzBuzz = IntStream.rangeClosed(1, 100)
                                 .mapToObj(n ->
                                         (n % 15 == 0) ? "FizzBuzz" :
                                         (n % 3 == 0) ? "Fizz" :
                                         (n % 5 == 0) ? "Buzz" :
                                         String.valueOf(n))
                                 .collect(Collectors.toList());
long count = list.parallelStream()
                 .filter(s -> s.startsWith("C"))
                 .mapToInt(s -> s.length())
                 .sum();


 

Optional

if (lang == null) {
    lang = "en"
}
String lang = value.orElse("en");
String lang = value.orElseGet(() -> {
    return "en";
});
String lang = "en";
Optional<String> value = getConfigValue("lang");
if (value.isPresent()) {
    lang = value.get();
} 
public Optional<String> getConfigValue(String key) {
    if (!containsKey(key)) {
        return Optional.empty();
    }
    return Optional.of(getValue(key));
}


Date and Time

ZonedDateTime now = ZonedDateTime.now();
  //=> 2015-05-24T23:13:17.254+09:00[Asia/Tokyo]

ZonedDateTime t1 = now.withMinute(0).withSecond(0).withNano(0);
  //=> 2015-05-24T23:00+09:00[Asia/Tokyo]

ZonedDateTime t2 = now.with(TemporalAdjusters.lastDayOfMonth());
  //=> 2015-05-31T23:13:17.254+09:00[Asia/Tokyo]

ZonedDateTime t3 = now.plusYears(1).minusHours(2);
  //=> 2016-05-24T21:13:17.254+09:00[Asia/Tokyo]

ZonedDateTime t = ZonedDateTime.of(2015, 5, 24, 23, 13, 52, 0, ZoneId.of("Asia/Tokyo"));
t.getYear();         //=> 2015
t.getMonth();        //=> Month.MAY
t.getMonthValue();   //=> 5  (0始まりではない)
t.getDayOfYear();    //=> 144
t.getDayOfMonth();   //=> 24
t.getDayOfWeek();    //=> DayOfWeek.SUNDAY
t.getHour();         //=> 23
t.getMinute();       //=> 13
t.getSecond();       //=> 52
t.getNano();         //=> 0
t.getZone().getId(); //=> "Asia/Tokyo"
 
// 太平洋標準時の夏時間開始2時間前 2015-03-08T00:00-08:00[America/Los_Angeles]
ZonedDateTime t = ZonedDateTime.of(2015, 3, 8, 0, 0, 0, 0, ZoneId.of("America/Los_Angeles"));

// 1時間ずつ進めると、2:00 PST になると同時に 3:00 PDT に飛ぶ
ZonedDateTime t1 = t.plusHours(1);  //=> 2015-03-08T01:00-08:00[America/Los_Angeles]
ZonedDateTime t2 = t.plusHours(2);  //=> 2015-03-08T03:00-07:00[America/Los_Angeles]
ZonedDateTime t3 = t.plusHours(3);  //=> 2015-03-08T04:00-07:00[America/Los_Angeles]

// Duration は24時間分、Period はローカル時間で1日分だけ進める
ZonedDateTime next1 = t.plus(Duration.ofDays(1L));  //=> 2015-03-09T01:00-07:00[America/Los_Angeles]
ZonedDateTime next2 = t.plus(Period.ofDays(1));     //=> 2015-03-09T00:00-07:00[America/Los_Angeles]
String.join。
// いずれも "A, B, C"
String.join(", ", "A", "B", "C");
String.join(", ", new String[]{"A", "B", "C"});
String.join(", ", Arrays.asList("A", "B", "C"));
Base64。
Base64.Encoder encoder = Base64.getEncoder();
String original = username + ":" + password;
String encoded = encoder.encodeToString(original.getBytes(StandardCharsets.UTF_8));
Files.lines。
Path path = Paths.get("/path/to/file.txt");
try (Stream<String> lines = Files.lines(path)) {
    lines.forEach(System.out::println);
} catch (IOException e) {
}


参考 https://qiita.com/oohira/items/9c13f92815266cc5112c