Java versions
versions3Java8Features
- Path
- pkg2versions/versions3Java8Features.java
- Package
- pkg2versions
- Study order
- 3
- Run
- Single-file source launch
- Command
- java pkg2versions/versions3Java8Features.java
- Version in the filename
- Java 8
- Example
- Java 8 example
- Requires
- Java 8
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg2versions;2 3/*4 * versions3Java8Features.java (2014) -- the most important modern release5 * ----------------------------------------------------------------6 * FEATURES & WHY:7 * - Lambdas : functions as values; concise behavior.8 * - Streams API : declarative bulk data processing.9 * - Optional : explicit absence; avoid NullPointerException.10 * - Default methods : evolve interfaces without breaking implementers.11 * - Method references : shorthand for lambdas.12 * - java.time : modern, immutable date/time API.13 */14import java.util.*;15import java.util.stream.*;16import java.time.*;17 18public class versions3Java8Features {19 20 interface Named {21 String name();22 default String shout() { return name().toUpperCase(); } // default method23 }24 25 public static void main(String[] args) {26 // Lambda implementing a functional interface27 Named n = () -> "java8";28 System.out.println("default method: " + n.shout());29 30 // Streams31 List<Integer> evens = IntStream.rangeClosed(1, 10)32 .filter(x -> x % 2 == 0)33 .boxed()34 .collect(Collectors.toList());35 System.out.println("evens 1..10: " + evens);36 37 // Method reference + collector38 String joined = Stream.of("a", "b", "c").map(String::toUpperCase).collect(Collectors.joining("-"));39 System.out.println("joined: " + joined);40 41 // Optional42 Optional<String> first = evens.stream().filter(x -> x > 100).map(String::valueOf).findFirst();43 System.out.println("optional: " + first.orElse("none"));44 45 // java.time46 LocalDate today = LocalDate.of(2024, 1, 15);47 System.out.println("plus 2 weeks: " + today.plusWeeks(2) + " | day: " + today.getDayOfWeek());48 Duration d = Duration.ofHours(2).plusMinutes(30);49 System.out.println("duration minutes: " + d.toMinutes());50 }51}