{"id":13471169,"url":"https://github.com/winterbe/java8-tutorial","last_synced_at":"2025-04-25T14:44:27.912Z","repository":{"id":15078176,"uuid":"17804584","full_name":"winterbe/java8-tutorial","owner":"winterbe","description":"Modern Java - A Guide to Java 8","archived":false,"fork":false,"pushed_at":"2023-08-11T18:44:34.000Z","size":149,"stargazers_count":16759,"open_issues_count":20,"forks_count":4044,"subscribers_count":990,"default_branch":"master","last_synced_at":"2025-04-24T04:17:57.883Z","etag":null,"topics":["guide","java","java-8","lambda-expressions","learning","parallel-streams","stream","tutorial"],"latest_commit_sha":null,"homepage":"http://winterbe.com","language":"Java","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/winterbe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2014-03-16T17:25:43.000Z","updated_at":"2025-04-23T13:23:34.000Z","dependencies_parsed_at":"2023-01-13T18:14:53.352Z","dependency_job_id":"360d03cb-4df3-4781-b415-d4d9c145a0d6","html_url":"https://github.com/winterbe/java8-tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/winterbe%2Fjava8-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/winterbe%2Fjava8-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/winterbe%2Fjava8-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/winterbe%2Fjava8-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/winterbe","download_url":"https://codeload.github.com/winterbe/java8-tutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250560061,"owners_count":21450173,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["guide","java","java-8","lambda-expressions","learning","parallel-streams","stream","tutorial"],"created_at":"2024-07-31T16:00:40.938Z","updated_at":"2025-04-24T04:18:02.113Z","avatar_url":"https://github.com/winterbe.png","language":"Java","readme":"# Modern Java - A Guide to Java 8\n_This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/)._\n\n\u003e **You should also read my [Java 11 Tutorial](https://winterbe.com/posts/2018/09/24/java-11-tutorial/) (including new language and API features from Java 9, 10 and 11).**\n\nWelcome to my introduction to [Java 8](https://jdk8.java.net/). This tutorial guides you step by step through all new language features. Backed by short and simple code samples you'll learn how to use default interface methods, lambda expressions, method references and repeatable annotations. At the end of the article you'll be familiar with the most recent [API](http://download.java.net/jdk8/docs/api/) changes like streams, functional interfaces, map extensions and the new Date API. **No walls of text, just a bunch of commented code snippets. Enjoy!**\n\n---\n\n\u003cp align=\"center\"\u003e\n ★★★ Like this project? Leave a star, \u003ca href=\"https://twitter.com/winterbe_\"\u003efollow on Twitter\u003c/a\u003e or \u003ca href=\"https://www.paypal.me/winterbe\"\u003edonate\u003c/a\u003e to support my work. Thanks! ★★★\n\u003c/p\u003e\n\n---\n\n## Table of Contents\n\n* [Default Methods for Interfaces](#default-methods-for-interfaces)\n* [Lambda expressions](#lambda-expressions)\n* [Functional Interfaces](#functional-interfaces)\n* [Method and Constructor References](#method-and-constructor-references)\n* [Lambda Scopes](#lambda-scopes)\n  * [Accessing local variables](#accessing-local-variables)\n  * [Accessing fields and static variables](#accessing-fields-and-static-variables)\n  * [Accessing Default Interface Methods](#accessing-default-interface-methods)\n* [Built-in Functional Interfaces](#built-in-functional-interfaces)\n  * [Predicates](#predicates)\n  * [Functions](#functions)\n  * [Suppliers](#suppliers)\n  * [Consumers](#consumers)\n  * [Comparators](#comparators)\n* [Optionals](#optionals)\n* [Streams](#streams)\n  * [Filter](#filter)\n  * [Sorted](#sorted)\n  * [Map](#map)\n  * [Match](#match)\n  * [Count](#count)\n  * [Reduce](#reduce)\n* [Parallel Streams](#parallel-streams)\n  * [Sequential Sort](#sequential-sort)\n  * [Parallel Sort](#parallel-sort)\n* [Maps](#maps)\n* [Date API](#date-api)\n  * [Clock](#clock)\n  * [Timezones](#timezones)\n  * [LocalTime](#localtime)\n  * [LocalDate](#localdate)\n  * [LocalDateTime](#localdatetime)\n* [Annotations](#annotations)\n* [Where to go from here?](#where-to-go-from-here)\n\n## Default Methods for Interfaces\n\nJava 8 enables us to add non-abstract method implementations to interfaces by utilizing the `default` keyword. This feature is also known as [virtual extension methods](http://stackoverflow.com/a/24102730). \n\nHere is our first example:\n\n```java\ninterface Formula {\n    double calculate(int a);\n\n    default double sqrt(int a) {\n        return Math.sqrt(a);\n    }\n}\n```\n\nBesides the abstract method `calculate` the interface `Formula` also defines the default method `sqrt`. Concrete classes only have to implement the abstract method `calculate`. The default method `sqrt` can be used out of the box.\n\n```java\nFormula formula = new Formula() {\n    @Override\n    public double calculate(int a) {\n        return sqrt(a * 100);\n    }\n};\n\nformula.calculate(100);     // 100.0\nformula.sqrt(16);           // 4.0\n```\n\nThe formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calculation of `sqrt(a * 100)`. As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8.\n\n\n## Lambda expressions\n\nLet's start with a simple example of how to sort a list of strings in prior versions of Java:\n\n```java\nList\u003cString\u003e names = Arrays.asList(\"peter\", \"anna\", \"mike\", \"xenia\");\n\nCollections.sort(names, new Comparator\u003cString\u003e() {\n    @Override\n    public int compare(String a, String b) {\n        return b.compareTo(a);\n    }\n});\n```\n\nThe static utility method `Collections.sort` accepts a list and a comparator in order to sort the elements of the given list. You often find yourself creating anonymous comparators and pass them to the sort method.\n\nInstead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, **lambda expressions**:\n\n```java\nCollections.sort(names, (String a, String b) -\u003e {\n    return b.compareTo(a);\n});\n```\n\nAs you can see the code is much shorter and easier to read. But it gets even shorter:\n\n```java\nCollections.sort(names, (String a, String b) -\u003e b.compareTo(a));\n```\n\nFor one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even shorter:\n\n```java\nnames.sort((a, b) -\u003e b.compareTo(a));\n```\n\nList now has a `sort` method. Also the java compiler is aware of the parameter types so you can skip them as well. Let's dive deeper into how lambda expressions can be used in the wild.\n\n\n## Functional Interfaces\n\nHow does lambda expressions fit into Java's type system? Each lambda corresponds to a given type, specified by an interface. A so called _functional interface_ must contain **exactly one abstract method** declaration. Each lambda expression of that type will be matched to this abstract method. Since default methods are not abstract you're free to add default methods to your functional interface.\n\nWe can use arbitrary interfaces as lambda expressions as long as the interface only contains one abstract method. To ensure that your interface meet the requirements, you should add the `@FunctionalInterface` annotation. The compiler is aware of this annotation and throws a compiler error as soon as you try to add a second abstract method declaration to the interface.\n\nExample:\n\n```java\n@FunctionalInterface\ninterface Converter\u003cF, T\u003e {\n    T convert(F from);\n}\n```\n\n```java\nConverter\u003cString, Integer\u003e converter = (from) -\u003e Integer.valueOf(from);\nInteger converted = converter.convert(\"123\");\nSystem.out.println(converted);    // 123\n```\n\nKeep in mind that the code is also valid if the `@FunctionalInterface` annotation would be omitted.\n\n\n## Method and Constructor References\n\nThe above example code can be further simplified by utilizing static method references:\n\n```java\nConverter\u003cString, Integer\u003e converter = Integer::valueOf;\nInteger converted = converter.convert(\"123\");\nSystem.out.println(converted);   // 123\n```\n\nJava 8 enables you to pass references of methods or constructors via the `::` keyword. The above example shows how to reference a static method. But we can also reference object methods:\n\n```java\nclass Something {\n    String startsWith(String s) {\n        return String.valueOf(s.charAt(0));\n    }\n}\n```\n\n```java\nSomething something = new Something();\nConverter\u003cString, String\u003e converter = something::startsWith;\nString converted = converter.convert(\"Java\");\nSystem.out.println(converted);    // \"J\"\n```\n\nLet's see how the `::` keyword works for constructors. First we define an example class with different constructors:\n\n```java\nclass Person {\n    String firstName;\n    String lastName;\n\n    Person() {}\n\n    Person(String firstName, String lastName) {\n        this.firstName = firstName;\n        this.lastName = lastName;\n    }\n}\n```\n\nNext we specify a person factory interface to be used for creating new persons:\n\n```java\ninterface PersonFactory\u003cP extends Person\u003e {\n    P create(String firstName, String lastName);\n}\n```\n\nInstead of implementing the factory manually, we glue everything together via constructor references:\n\n```java\nPersonFactory\u003cPerson\u003e personFactory = Person::new;\nPerson person = personFactory.create(\"Peter\", \"Parker\");\n```\n\nWe create a reference to the Person constructor via `Person::new`. The Java compiler automatically chooses the right constructor by matching the signature of `PersonFactory.create`.\n\n## Lambda Scopes\n\nAccessing outer scope variables from lambda expressions is very similar to anonymous objects. You can access final variables from the local outer scope as well as instance fields and static variables.\n\n### Accessing local variables\n\nWe can read final local variables from the outer scope of lambda expressions:\n\n```java\nfinal int num = 1;\nConverter\u003cInteger, String\u003e stringConverter =\n        (from) -\u003e String.valueOf(from + num);\n\nstringConverter.convert(2);     // 3\n```\n\nBut different to anonymous objects the variable `num` does not have to be declared final. This code is also valid:\n\n```java\nint num = 1;\nConverter\u003cInteger, String\u003e stringConverter =\n        (from) -\u003e String.valueOf(from + num);\n\nstringConverter.convert(2);     // 3\n```\n\nHowever `num` must be implicitly final for the code to compile. The following code does **not** compile:\n\n```java\nint num = 1;\nConverter\u003cInteger, String\u003e stringConverter =\n        (from) -\u003e String.valueOf(from + num);\nnum = 3;\n```\n\nWriting to `num` from within the lambda expression is also prohibited.\n\n### Accessing fields and static variables\n\nIn contrast to local variables, we have both read and write access to instance fields and static variables from within lambda expressions. This behaviour is well known from anonymous objects.\n\n```java\nclass Lambda4 {\n    static int outerStaticNum;\n    int outerNum;\n\n    void testScopes() {\n        Converter\u003cInteger, String\u003e stringConverter1 = (from) -\u003e {\n            outerNum = 23;\n            return String.valueOf(from);\n        };\n\n        Converter\u003cInteger, String\u003e stringConverter2 = (from) -\u003e {\n            outerStaticNum = 72;\n            return String.valueOf(from);\n        };\n    }\n}\n```\n\n### Accessing Default Interface Methods\n\nRemember the formula example from the first section? Interface `Formula` defines a default method `sqrt` which can be accessed from each formula instance including anonymous objects. This does not work with lambda expressions.\n\nDefault methods **cannot** be accessed from within lambda expressions. The following code does not compile:\n\n```java\nFormula formula = (a) -\u003e sqrt(a * 100);\n```\n\n\n## Built-in Functional Interfaces\n\nThe JDK 1.8 API contains many built-in functional interfaces. Some of them are well known from older versions of Java like `Comparator` or `Runnable`. Those existing interfaces are extended to enable Lambda support via the `@FunctionalInterface` annotation.\n\nBut the Java 8 API is also full of new functional interfaces to make your life easier. Some of those new interfaces are well known from the [Google Guava](https://code.google.com/p/guava-libraries/) library. Even if you're familiar with this library you should keep a close eye on how those interfaces are extended by some useful method extensions.\n\n### Predicates\n\nPredicates are boolean-valued functions of one argument. The interface contains various default methods for composing predicates to complex logical terms (and, or, negate)\n\n```java\nPredicate\u003cString\u003e predicate = (s) -\u003e s.length() \u003e 0;\n\npredicate.test(\"foo\");              // true\npredicate.negate().test(\"foo\");     // false\n\nPredicate\u003cBoolean\u003e nonNull = Objects::nonNull;\nPredicate\u003cBoolean\u003e isNull = Objects::isNull;\n\nPredicate\u003cString\u003e isEmpty = String::isEmpty;\nPredicate\u003cString\u003e isNotEmpty = isEmpty.negate();\n```\n\n### Functions\n\nFunctions accept one argument and produce a result. Default methods can be used to chain multiple functions together (compose, andThen).\n\n```java\nFunction\u003cString, Integer\u003e toInteger = Integer::valueOf;\nFunction\u003cString, String\u003e backToString = toInteger.andThen(String::valueOf);\n\nbackToString.apply(\"123\");     // \"123\"\n```\n\n### Suppliers\n\nSuppliers produce a result of a given generic type. Unlike Functions, Suppliers don't accept arguments.\n\n```java\nSupplier\u003cPerson\u003e personSupplier = Person::new;\npersonSupplier.get();   // new Person\n```\n\n### Consumers\n\nConsumers represent operations to be performed on a single input argument.\n\n```java\nConsumer\u003cPerson\u003e greeter = (p) -\u003e System.out.println(\"Hello, \" + p.firstName);\ngreeter.accept(new Person(\"Luke\", \"Skywalker\"));\n```\n\n### Comparators\n\nComparators are well known from older versions of Java. Java 8 adds various default methods to the interface.\n\n```java\nComparator\u003cPerson\u003e comparator = (p1, p2) -\u003e p1.firstName.compareTo(p2.firstName);\n\nPerson p1 = new Person(\"John\", \"Doe\");\nPerson p2 = new Person(\"Alice\", \"Wonderland\");\n\ncomparator.compare(p1, p2);             // \u003e 0\ncomparator.reversed().compare(p1, p2);  // \u003c 0\n```\n\n## Optionals\n\nOptionals are not functional interfaces, but nifty utilities to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work.\n\nOptional is a simple container for a value which may be null or non-null. Think of a method which may return a non-null result but sometimes return nothing. Instead of returning `null` you return an `Optional` in Java 8.\n\n```java\nOptional\u003cString\u003e optional = Optional.of(\"bam\");\n\noptional.isPresent();           // true\noptional.get();                 // \"bam\"\noptional.orElse(\"fallback\");    // \"bam\"\n\noptional.ifPresent((s) -\u003e System.out.println(s.charAt(0)));     // \"b\"\n```\n\n## Streams\n\nA `java.util.Stream` represents a sequence of elements on which one or more operations can be performed. Stream operations are either _intermediate_ or _terminal_. While terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a `java.util.Collection` like lists or sets (maps are not supported). Stream operations can either be executed sequentially or parallely.\n\n\u003e Streams are extremely powerful, so I wrote a separate [Java 8 Streams Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/). **You should also check out [Sequency](https://github.com/winterbe/sequency) as a similiar library for the web.**\n\nLet's first look how sequential streams work. First we create a sample source in form of a list of strings:\n\n```java\nList\u003cString\u003e stringCollection = new ArrayList\u003c\u003e();\nstringCollection.add(\"ddd2\");\nstringCollection.add(\"aaa2\");\nstringCollection.add(\"bbb1\");\nstringCollection.add(\"aaa1\");\nstringCollection.add(\"bbb3\");\nstringCollection.add(\"ccc\");\nstringCollection.add(\"bbb2\");\nstringCollection.add(\"ddd1\");\n```\n\nCollections in Java 8 are extended so you can simply create streams either by calling `Collection.stream()` or `Collection.parallelStream()`. The following sections explain the most common stream operations.\n\n### Filter\n\nFilter accepts a predicate to filter all elements of the stream. This operation is _intermediate_ which enables us to call another stream operation (`forEach`) on the result. ForEach accepts a consumer to be executed for each element in the filtered stream. ForEach is a terminal operation. It's `void`, so we cannot call another stream operation.\n\n```java\nstringCollection\n    .stream()\n    .filter((s) -\u003e s.startsWith(\"a\"))\n    .forEach(System.out::println);\n\n// \"aaa2\", \"aaa1\"\n```\n\n### Sorted\n\nSorted is an _intermediate_ operation which returns a sorted view of the stream. The elements are sorted in natural order unless you pass a custom `Comparator`.\n\n```java\nstringCollection\n    .stream()\n    .sorted()\n    .filter((s) -\u003e s.startsWith(\"a\"))\n    .forEach(System.out::println);\n\n// \"aaa1\", \"aaa2\"\n```\n\nKeep in mind that `sorted` does only create a sorted view of the stream without manipulating the ordering of the backed collection. The ordering of `stringCollection` is untouched:\n\n```java\nSystem.out.println(stringCollection);\n// ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1\n```\n\n### Map\n\nThe _intermediate_ operation `map` converts each element into another object via the given function. The following example converts each string into an upper-cased string. But you can also use `map` to transform each object into another type. The generic type of the resulting stream depends on the generic type of the function you pass to `map`.\n\n```java\nstringCollection\n    .stream()\n    .map(String::toUpperCase)\n    .sorted((a, b) -\u003e b.compareTo(a))\n    .forEach(System.out::println);\n\n// \"DDD2\", \"DDD1\", \"CCC\", \"BBB3\", \"BBB2\", \"AAA2\", \"AAA1\"\n```\n\n### Match\n\nVarious matching operations can be used to check whether a certain predicate matches the stream. All of those operations are _terminal_ and return a boolean result.\n\n```java\nboolean anyStartsWithA =\n    stringCollection\n        .stream()\n        .anyMatch((s) -\u003e s.startsWith(\"a\"));\n\nSystem.out.println(anyStartsWithA);      // true\n\nboolean allStartsWithA =\n    stringCollection\n        .stream()\n        .allMatch((s) -\u003e s.startsWith(\"a\"));\n\nSystem.out.println(allStartsWithA);      // false\n\nboolean noneStartsWithZ =\n    stringCollection\n        .stream()\n        .noneMatch((s) -\u003e s.startsWith(\"z\"));\n\nSystem.out.println(noneStartsWithZ);      // true\n```\n\n#### Count\n\nCount is a _terminal_ operation returning the number of elements in the stream as a `long`.\n\n```java\nlong startsWithB =\n    stringCollection\n        .stream()\n        .filter((s) -\u003e s.startsWith(\"b\"))\n        .count();\n\nSystem.out.println(startsWithB);    // 3\n```\n\n\n### Reduce\n\nThis _terminal_ operation performs a reduction on the elements of the stream with the given function. The result is an `Optional` holding the reduced value.\n\n```java\nOptional\u003cString\u003e reduced =\n    stringCollection\n        .stream()\n        .sorted()\n        .reduce((s1, s2) -\u003e s1 + \"#\" + s2);\n\nreduced.ifPresent(System.out::println);\n// \"aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2\"\n```\n\n## Parallel Streams\n\nAs mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed concurrently on multiple threads.\n\nThe following example demonstrates how easy it is to increase the performance by using parallel streams.\n\nFirst we create a large list of unique elements:\n\n```java\nint max = 1000000;\nList\u003cString\u003e values = new ArrayList\u003c\u003e(max);\nfor (int i = 0; i \u003c max; i++) {\n    UUID uuid = UUID.randomUUID();\n    values.add(uuid.toString());\n}\n```\n\nNow we measure the time it takes to sort a stream of this collection.\n\n### Sequential Sort\n\n```java\nlong t0 = System.nanoTime();\n\nlong count = values.stream().sorted().count();\nSystem.out.println(count);\n\nlong t1 = System.nanoTime();\n\nlong millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);\nSystem.out.println(String.format(\"sequential sort took: %d ms\", millis));\n\n// sequential sort took: 899 ms\n```\n\n### Parallel Sort\n\n```java\nlong t0 = System.nanoTime();\n\nlong count = values.parallelStream().sorted().count();\nSystem.out.println(count);\n\nlong t1 = System.nanoTime();\n\nlong millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);\nSystem.out.println(String.format(\"parallel sort took: %d ms\", millis));\n\n// parallel sort took: 472 ms\n```\n\nAs you can see both code snippets are almost identical but the parallel sort is roughly 50% faster. All you have to do is change `stream()` to `parallelStream()`.\n\n## Maps\n\nAs already mentioned maps do not directly support streams. There's no `stream()` method available on the `Map` interface itself, however you can create specialized streams upon the keys, values or entries of a map via `map.keySet().stream()`, `map.values().stream()` and `map.entrySet().stream()`. \n\nFurthermore maps support various new and useful methods for doing common tasks.\n\n```java\nMap\u003cInteger, String\u003e map = new HashMap\u003c\u003e();\n\nfor (int i = 0; i \u003c 10; i++) {\n    map.putIfAbsent(i, \"val\" + i);\n}\n\nmap.forEach((id, val) -\u003e System.out.println(val));\n```\n\nThe above code should be self-explaining: `putIfAbsent` prevents us from writing additional if null checks; `forEach` accepts a consumer to perform operations for each value of the map.\n\nThis example shows how to compute code on the map by utilizing functions:\n\n```java\nmap.computeIfPresent(3, (num, val) -\u003e val + num);\nmap.get(3);             // val33\n\nmap.computeIfPresent(9, (num, val) -\u003e null);\nmap.containsKey(9);     // false\n\nmap.computeIfAbsent(23, num -\u003e \"val\" + num);\nmap.containsKey(23);    // true\n\nmap.computeIfAbsent(3, num -\u003e \"bam\");\nmap.get(3);             // val33\n```\n\nNext, we learn how to remove entries for a given key, only if it's currently mapped to a given value:\n\n```java\nmap.remove(3, \"val3\");\nmap.get(3);             // val33\n\nmap.remove(3, \"val33\");\nmap.get(3);             // null\n```\n\nAnother helpful method:\n\n```java\nmap.getOrDefault(42, \"not found\");  // not found\n```\n\nMerging entries of a map is quite easy:\n\n```java\nmap.merge(9, \"val9\", (value, newValue) -\u003e value.concat(newValue));\nmap.get(9);             // val9\n\nmap.merge(9, \"concat\", (value, newValue) -\u003e value.concat(newValue));\nmap.get(9);             // val9concat\n```\n\nMerge either put the key/value into the map if no entry for the key exists, or the merging function will be called to change the existing value.\n\n\n## Date API\n\nJava 8 contains a brand new date and time API under the package `java.time`. The new Date API is comparable with the [Joda-Time](http://www.joda.org/joda-time/) library, however it's [not the same](http://blog.joda.org/2009/11/why-jsr-310-isn-joda-time_4941.html). The following examples cover the most important parts of this new API.\n\n### Clock\n\nClock provides access to the current date and time. Clocks are aware of a timezone and may be used instead of `System.currentTimeMillis()` to retrieve the current time in milliseconds since Unix EPOCH. Such an instantaneous point on the time-line is also represented by the class `Instant`. Instants can be used to create legacy `java.util.Date` objects.\n\n```java\nClock clock = Clock.systemDefaultZone();\nlong millis = clock.millis();\n\nInstant instant = clock.instant();\nDate legacyDate = Date.from(instant);   // legacy java.util.Date\n```\n\n### Timezones\n\nTimezones are represented by a `ZoneId`. They can easily be accessed via static factory methods. Timezones define the offsets which are important to convert between instants and local dates and times.\n\n```java\nSystem.out.println(ZoneId.getAvailableZoneIds());\n// prints all available timezone ids\n\nZoneId zone1 = ZoneId.of(\"Europe/Berlin\");\nZoneId zone2 = ZoneId.of(\"Brazil/East\");\nSystem.out.println(zone1.getRules());\nSystem.out.println(zone2.getRules());\n\n// ZoneRules[currentStandardOffset=+01:00]\n// ZoneRules[currentStandardOffset=-03:00]\n```\n\n### LocalTime\n\nLocalTime represents a time without a timezone, e.g. 10pm or 17:30:15. The following example creates two local times for the timezones defined above. Then we compare both times and calculate the difference in hours and minutes between both times.\n\n```java\nLocalTime now1 = LocalTime.now(zone1);\nLocalTime now2 = LocalTime.now(zone2);\n\nSystem.out.println(now1.isBefore(now2));  // false\n\nlong hoursBetween = ChronoUnit.HOURS.between(now1, now2);\nlong minutesBetween = ChronoUnit.MINUTES.between(now1, now2);\n\nSystem.out.println(hoursBetween);       // -3\nSystem.out.println(minutesBetween);     // -239\n```\n\nLocalTime comes with various factory methods to simplify the creation of new instances, including parsing of time strings.\n\n```java\nLocalTime late = LocalTime.of(23, 59, 59);\nSystem.out.println(late);       // 23:59:59\n\nDateTimeFormatter germanFormatter =\n    DateTimeFormatter\n        .ofLocalizedTime(FormatStyle.SHORT)\n        .withLocale(Locale.GERMAN);\n\nLocalTime leetTime = LocalTime.parse(\"13:37\", germanFormatter);\nSystem.out.println(leetTime);   // 13:37\n```\n\n### LocalDate\n\nLocalDate represents a distinct date, e.g. 2014-03-11. It's immutable and works exactly analog to LocalTime. The sample demonstrates how to calculate new dates by adding or subtracting days, months or years. Keep in mind that each manipulation returns a new instance.\n\n```java\nLocalDate today = LocalDate.now();\nLocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);\nLocalDate yesterday = tomorrow.minusDays(2);\n\nLocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);\nDayOfWeek dayOfWeek = independenceDay.getDayOfWeek();\nSystem.out.println(dayOfWeek);    // FRIDAY\n```\n\nParsing a LocalDate from a string is just as simple as parsing a LocalTime:\n\n```java\nDateTimeFormatter germanFormatter =\n    DateTimeFormatter\n        .ofLocalizedDate(FormatStyle.MEDIUM)\n        .withLocale(Locale.GERMAN);\n\nLocalDate xmas = LocalDate.parse(\"24.12.2014\", germanFormatter);\nSystem.out.println(xmas);   // 2014-12-24\n```\n\n### LocalDateTime\n\nLocalDateTime represents a date-time. It combines date and time as seen in the above sections into one instance. `LocalDateTime` is immutable and works similar to LocalTime and LocalDate. We can utilize methods for retrieving certain fields from a date-time:\n\n```java\nLocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);\n\nDayOfWeek dayOfWeek = sylvester.getDayOfWeek();\nSystem.out.println(dayOfWeek);      // WEDNESDAY\n\nMonth month = sylvester.getMonth();\nSystem.out.println(month);          // DECEMBER\n\nlong minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);\nSystem.out.println(minuteOfDay);    // 1439\n```\n\nWith the additional information of a timezone it can be converted to an instant. Instants can easily be converted to legacy dates of type `java.util.Date`.\n\n```java\nInstant instant = sylvester\n        .atZone(ZoneId.systemDefault())\n        .toInstant();\n\nDate legacyDate = Date.from(instant);\nSystem.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014\n```\n\nFormatting date-times works just like formatting dates or times. Instead of using pre-defined formats we can create formatters from custom patterns.\n\n```java\nDateTimeFormatter formatter =\n    DateTimeFormatter\n        .ofPattern(\"MMM dd, yyyy - HH:mm\");\n\nLocalDateTime parsed = LocalDateTime.parse(\"Nov 03, 2014 - 07:13\", formatter);\nString string = formatter.format(parsed);\nSystem.out.println(string);     // Nov 03, 2014 - 07:13\n```\n\nUnlike `java.text.NumberFormat` the new `DateTimeFormatter` is immutable and **thread-safe**.\n\nFor details on the pattern syntax read [here](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html).\n\n\n## Annotations\n\nAnnotations in Java 8 are repeatable. Let's dive directly into an example to figure that out.\n\nFirst, we define a wrapper annotation which holds an array of the actual annotations:\n\n```java\n@interface Hints {\n    Hint[] value();\n}\n\n@Repeatable(Hints.class)\n@interface Hint {\n    String value();\n}\n```\nJava 8 enables us to use multiple annotations of the same type by declaring the annotation `@Repeatable`.\n\n### Variant 1: Using the container annotation (old school)\n\n```java\n@Hints({@Hint(\"hint1\"), @Hint(\"hint2\")})\nclass Person {}\n```\n\n### Variant 2: Using repeatable annotations (new school)\n\n```java\n@Hint(\"hint1\")\n@Hint(\"hint2\")\nclass Person {}\n```\n\nUsing variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation information via reflection.\n\n```java\nHint hint = Person.class.getAnnotation(Hint.class);\nSystem.out.println(hint);                   // null\n\nHints hints1 = Person.class.getAnnotation(Hints.class);\nSystem.out.println(hints1.value().length);  // 2\n\nHint[] hints2 = Person.class.getAnnotationsByType(Hint.class);\nSystem.out.println(hints2.length);          // 2\n```\n\nAlthough we never declared the `@Hints` annotation on the `Person` class, it's still readable via `getAnnotation(Hints.class)`. However, the more convenient method is `getAnnotationsByType` which grants direct access to all annotated `@Hint` annotations.\n\n\nFurthermore the usage of annotations in Java 8 is expanded to two new targets:\n\n```java\n@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})\n@interface MyAnnotation {}\n```\n\n## Where to go from here?\n\nMy programming guide to Java 8 ends here. If you want to learn more about all the new classes and features of the JDK 8 API, check out my [JDK8 API Explorer](http://winterbe.com/projects/java8-explorer/). It helps you figuring out all the new classes and hidden gems of JDK 8, like `Arrays.parallelSort`, `StampedLock` and `CompletableFuture` - just to name a few.\n\nI've also published a bunch of follow-up articles on my [blog](http://winterbe.com) that might be interesting to you:\n\n- [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/)\n- [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/)\n- [Java 8 Concurrency Tutorial: Threads and Executors](http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/)\n- [Java 8 Concurrency Tutorial: Synchronization and Locks](http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/)\n- [Java 8 Concurrency Tutorial: Atomic Variables and ConcurrentMap](http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/)\n- [Java 8 API by Example: Strings, Numbers, Math and Files](http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/)\n- [Avoid Null Checks in Java 8](http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/)\n- [Fixing Java 8 Stream Gotchas with IntelliJ IDEA](http://winterbe.com/posts/2015/03/05/fixing-java-8-stream-gotchas-with-intellij-idea/)\n- [Using Backbone.js with Java 8 Nashorn](http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/)\n\nYou should [follow me on Twitter](https://twitter.com/winterbe_). Thanks for reading!\n","funding_links":["https://www.paypal.me/winterbe"],"categories":["Java","Projects","Java/Kotlin","HarmonyOS","Java 程序设计","VII. Other","项目","Miscellaneous"],"sub_categories":["Miscellaneous","Windows Manager","网络服务_其他","1. Source code examples","杂项"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwinterbe%2Fjava8-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwinterbe%2Fjava8-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwinterbe%2Fjava8-tutorial/lists"}