From 4796f987691f9a4da5ddd68d548b69b9b6d4c95c Mon Sep 17 00:00:00 2001 From: shubhamyeole Date: Tue, 13 Oct 2015 23:26:28 -0400 Subject: [PATCH 01/35] Added package custom --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 77642f01..f911407f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .DS_Store .idea *.iml -out \ No newline at end of file +out +/bin/ From 5ebecfcc8ce4b996bedc910c6edbea2c6ca04680 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 09:26:10 +0100 Subject: [PATCH 02/35] Publish the original Java 8 Tutorial --- README.md | 763 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 751 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 708d37d5..8a3d73fc 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,756 @@ -Java 8 Tutorial Examples -============== +# Modern Java - A Guide to Java 8 -This repository contains all code samples from the Java 8 related posts of my [blog](http://winterbe.com): +> [“Java is still not dead—and people are starting to figure that out.”](https://twitter.com/mreinhold/status/429603588525281280) + +Welcome 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! + +This article was originally posted on my [blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). + +## Default Methods for Interfaces + +Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the `default` keyword. This feature is also known as **Extension Methods**. Here is our first example: + +```java +interface Formula { + double calculate(int a); + + default double sqrt(int a) { + return Math.sqrt(a); + } +} +``` + +Besides 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. + +```java +Formula formula = new Formula() { + @Override + public double calculate(int a) { + return sqrt(a * 100); + } +}; + +formula.calculate(100); // 100.0 +formula.sqrt(16); // 4.0 +``` + +The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calucation 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. + + +## Lambda expressions + +Let's start with a simple example of how to sort a list of strings in prior versions of Java: + +```java +List names = Arrays.asList("peter", "anna", "mike", "xenia"); + +Collections.sort(names, new Comparator() { + @Override + public int compare(String a, String b) { + return b.compareTo(a); + } +}); +``` + +The 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. + +Instead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, **lambda expressions**: + +```java +Collections.sort(names, (String a, String b) -> { + return b.compareTo(a); +}); +``` + +As you can see the code is much shorter and easier to read. But it gets even shorter: + +```java +Collections.sort(names, (String a, String b) -> b.compareTo(a)); +``` + +For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even more shorter: + +```java +Collections.sort(names, (a, b) -> b.compareTo(a)); +``` + +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. + + +## Functional Interfaces + +How does lambda expressions fit into Javas 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. + +We 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. + +Example: + +```java +@FunctionalInterface +interface Converter { + T convert(F from); +} +``` + +```java +Converter converter = (from) -> Integer.valueOf(from); +Integer converted = converter.convert("123"); +System.out.println(converted); // 123 +``` + +Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be ommited. + + +## Method and Constructor References + +The above example code can be further simplified by utilizing static method references: + +```java +Converter converter = Integer::valueOf; +Integer converted = converter.convert("123"); +System.out.println(converted); // 123 +``` + +Java 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: + +```java +class Something { + String startsWith(String s) { + return String.valueOf(s.charAt(0)); + } +} +``` + +```java +Something something = new Something(); +Converter converter = something::startsWith; +String converted = converter.convert("Java"); +System.out.println(converted); // "J" +``` + +Let's see how the `::` keyword works for constructors. First we define an example bean with different constructors: + +```java +class Person { + String firstName; + String lastName; + + Person() {} + + Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } +} +``` + +Next we specify a person factory interface to be used for creating new persons: + +```java +interface PersonFactory

{ + P create(String firstName, String lastName); +} +``` + +Instead of implementing the factory manually, we glue everything together via constructor references: + +```java +PersonFactory personFactory = Person::new; +Person person = personFactory.create("Peter", "Parker"); +``` + +We 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`. + +## Lambda Scopes + +Accessing 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. + +### Accessing local variables + +We can read final local variables from the outer scope of lambda expressions: + +```java +final int num = 1; +Converter stringConverter = + (from) -> String.valueOf(from + num); + +stringConverter.convert(2); // 3 +``` + +But different to anonymous objects the variable `num` does not have to be declared final. This code is also valid: + +```java +int num = 1; +Converter stringConverter = + (from) -> String.valueOf(from + num); + +stringConverter.convert(2); // 3 +``` + +However `num` must be implicitly final for the code to compile. The following code does **not** compile: + +```java +int num = 1; +Converter stringConverter = + (from) -> String.valueOf(from + num); +num = 3; +``` + +Writing to `num` from within the lambda expression is also prohibited. + +### Accessing fields and static variables + +In constrast 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. + +```java +class Lambda4 { + static int outerStaticNum; + int outerNum; + + void testScopes() { + Converter stringConverter1 = (from) -> { + outerNum = 23; + return String.valueOf(from); + }; + + Converter stringConverter2 = (from) -> { + outerStaticNum = 72; + return String.valueOf(from); + }; + } +} +``` + +### Accessing Default Interface Methods + +Remember 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. + +Default methods **cannot** be accessed from within lambda expressions. The following code does not compile: + +```java +Formula formula = (a) -> sqrt( a * 100); +``` + + +## Built-in Functional Interfaces + +The 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. + +But 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. + +### Predicates + +Predicates are boolean-valued functions of one argument. The interface contains various default methods for composing predicates to complex logical terms (and, or, negate) + +```java +Predicate predicate = (s) -> s.length() > 0; + +predicate.test("foo"); // true +predicate.negate().test("foo"); // false + +Predicate nonNull = Objects::nonNull; +Predicate isNull = Objects::isNull; + +Predicate isEmpty = String::isEmpty; +Predicate isNotEmpty = isEmpty.negate(); +``` + +### Functions + +Functions accept one argument and produce a result. Default methods can be used to chain multiple functions together (compose, andThen). + +```java +Function toInteger = Integer::valueOf; +Function backToString = toInteger.andThen(String::valueOf); + +backToString.apply("123"); // "123" +``` + +### Suppliers + +Suppliers produce a result of a given generic type. Unlike Functions, Suppliers don't accept arguments. + +```java +Supplier personSupplier = Person::new; +personSupplier.get(); // new Person +``` + +### Consumers + +Consumers represents operations to be performed on a single input argument. + +```java +Consumer greeter = (p) -> System.out.println("Hello, " + p.firstName); +greeter.accept(new Person("Luke", "Skywalker")); +``` + +### Comparators + +Comparators are well known from older versions of Java. Java 8 adds various default methods to the interface. + +```java +Comparator comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); + +Person p1 = new Person("John", "Doe"); +Person p2 = new Person("Alice", "Wonderland"); + +comparator.compare(p1, p2); // > 0 +comparator.reversed().compare(p1, p2); // < 0 +``` + +### Optionals + +Optionals are not functional interfaces, instead it's a nifty utility to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work. + +Optional 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. + +```java +Optional optional = Optional.of("bam"); + +optional.isPresent(); // true +optional.get(); // "bam" +optional.orElse("fallback"); // "bam" + +optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" +``` + +## Streams + +A `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 sequential or parallel. + +Let's first look how sequential streams work. First we create a sample source in form of a list of strings: + +```java +List stringCollection = new ArrayList<>(); +stringCollection.add("ddd2"); +stringCollection.add("aaa2"); +stringCollection.add("bbb1"); +stringCollection.add("aaa1"); +stringCollection.add("bbb3"); +stringCollection.add("ccc"); +stringCollection.add("bbb2"); +stringCollection.add("ddd1"); +``` + +Collections 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. + +### Filter + +Filter 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. + +```java +stringCollection + .stream() + .filter((s) -> s.startsWith("a")) + .forEach(System.out::println); + +// "aaa2", "aaa1" +``` + +### Sorted + +Sorted 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`. + +```java +stringCollection + .stream() + .sorted() + .filter((s) -> s.startsWith("a")) + .forEach(System.out::println); + +// "aaa1", "aaa2" +``` + +Keep 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: + +```java +System.out.println(stringCollection); +// ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1 +``` + +### Map + +The _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`. + +```java +stringCollection + .stream() + .map(String::toUpperCase) + .sorted((a, b) -> b.compareTo(a)) + .forEach(System.out::println); + +// "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1" +``` + +### Match + +Various 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. + +```java +boolean anyStartsWithA = + stringCollection + .stream() + .anyMatch((s) -> s.startsWith("a")); + +System.out.println(anyStartsWithA); // true + +boolean allStartsWithA = + stringCollection + .stream() + .allMatch((s) -> s.startsWith("a")); + +System.out.println(allStartsWithA); // false + +boolean noneStartsWithZ = + stringCollection + .stream() + .noneMatch((s) -> s.startsWith("z")); + +System.out.println(noneStartsWithZ); // true +``` + +#### Count + +Count is a _terminal_ operation returning the number of elements in the stream as a `long`. + +```java +long startsWithB = + stringCollection + .stream() + .filter((s) -> s.startsWith("b")) + .count(); + +System.out.println(startsWithB); // 3 +``` + + +### Reduce + +This _terminal_ operation performs a reduction on the elements of the stream with the given function. The result is an `Optional` holding the reduced value. + +```java +Optional reduced = + stringCollection + .stream() + .sorted() + .reduce((s1, s2) -> s1 + "#" + s2); + +reduced.ifPresent(System.out::println); +// "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2" +``` + +## Parallel Streams + +As 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 concurrent on multiple threads. + +The following example demonstrates how easy it is to increase the performance by using parallel streams. + +First we create a large list of unique elements: + +```java +int max = 1000000; +List values = new ArrayList<>(max); +for (int i = 0; i < max; i++) { + UUID uuid = UUID.randomUUID(); + values.add(uuid.toString()); +} +``` + +Now we measure the time it takes to sort a stream of this collection. + +### Sequential Sort + +```java +long t0 = System.nanoTime(); + +long count = values.stream().sorted().count(); +System.out.println(count); + +long t1 = System.nanoTime(); + +long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); +System.out.println(String.format("sequential sort took: %d ms", millis)); + +// sequential sort took: 899 ms +``` + +### Parallel Sort + +```java +long t0 = System.nanoTime(); + +long count = values.parallelStream().sorted().count(); +System.out.println(count); + +long t1 = System.nanoTime(); + +long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); +System.out.println(String.format("parallel sort took: %d ms", millis)); + +// parallel sort took: 472 ms +``` + +As 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()`. + +## Map + +As already mentioned maps don't support streams. Instead maps now support various new and useful methods for doing common tasks. + +```java +Map map = new HashMap<>(); + +for (int i = 0; i < 10; i++) { + map.putIfAbsent(i, "val" + i); +} + +map.forEach((id, val) -> System.out.println(val)); +``` + +The 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. + +This example shows how to compute code on the map by utilizing functions: + +```java +map.computeIfPresent(3, (num, val) -> val + num); +map.get(3); // val33 + +map.computeIfPresent(9, (num, val) -> null); +map.containsKey(9); // false + +map.computeIfAbsent(23, num -> "val" + num); +map.containsKey(23); // true + +map.computeIfAbsent(3, num -> "bam"); +map.get(3); // val33 +``` + +Next, we learn how to remove entries for a a given key, only if it's currently mapped to a given value: + +```java +map.remove(3, "val3"); +map.get(3); // val33 + +map.remove(3, "val33"); +map.get(3); // null +``` + +Another helpful method: + +```java +map.getOrDefault(42, "not found"); // not found +``` + +Merging entries of a map is quite easy: + +```java +map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); +map.get(9); // val9 + +map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); +map.get(9); // val9concat +``` + +Merge 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. + + +## Date API + +Java 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. + +### Clock + +Clock 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 milliseconds. 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. + +```java +Clock clock = Clock.systemDefaultZone(); +long millis = clock.millis(); + +Instant instant = clock.instant(); +Date legacyDate = Date.from(instant); // legacy java.util.Date +``` + +### Timezones + +Timezones 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. + +```java +System.out.println(ZoneId.getAvailableZoneIds()); +// prints all available timezone ids + +ZoneId zone1 = ZoneId.of("Europe/Berlin"); +ZoneId zone2 = ZoneId.of("Brazil/East"); +System.out.println(zone1.getRules()); +System.out.println(zone2.getRules()); + +// ZoneRules[currentStandardOffset=+01:00] +// ZoneRules[currentStandardOffset=-03:00] +``` + +### LocalTime + +LocalTime 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. + +```java +LocalTime now1 = LocalTime.now(zone1); +LocalTime now2 = LocalTime.now(zone2); + +System.out.println(now1.isBefore(now2)); // false + +long hoursBetween = ChronoUnit.HOURS.between(now1, now2); +long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); + +System.out.println(hoursBetween); // -3 +System.out.println(minutesBetween); // -239 +``` + +LocalTime comes with various factory method to simplify the creation of new instances, including parsing of time strings. + +```java +LocalTime late = LocalTime.of(23, 59, 59); +System.out.println(late); // 23:59:59 + +DateTimeFormatter germanFormatter = + DateTimeFormatter + .ofLocalizedTime(FormatStyle.SHORT) + .withLocale(Locale.GERMAN); + +LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); +System.out.println(leetTime); // 13:37 +``` + +### LocalDate + +LocalDate 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 substracting days, months or years. Keep in mind that each manipulation returns a new instance. + +```java +LocalDate today = LocalDate.now(); +LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); +LocalDate yesterday = tomorrow.minusDays(2); + +LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); +DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); +System.out.println(dayOfWeek); // FRIDAY +``` + +Parsing a LocalDate from a string is just as simple as parsing a LocalTime: + +```java +DateTimeFormatter germanFormatter = + DateTimeFormatter + .ofLocalizedDate(FormatStyle.MEDIUM) + .withLocale(Locale.GERMAN); + +LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); +System.out.println(xmas); // 2014-12-24 +``` + +### LocalDateTime + +LocalDateTime 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: + +```java +LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); + +DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); +System.out.println(dayOfWeek); // WEDNESDAY + +Month month = sylvester.getMonth(); +System.out.println(month); // DECEMBER + +long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); +System.out.println(minuteOfDay); // 1439 +``` + +With 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`. + +```java +Instant instant = sylvester + .atZone(ZoneId.systemDefault()) + .toInstant(); + +Date legacyDate = Date.from(instant); +System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014 +``` + +Formatting date-times works just like formatting dates or times. Instead of using pre-defined formats we can create formatters from custom patterns. + +```java +DateTimeFormatter formatter = + DateTimeFormatter + .ofPattern("MMM dd, yyyy - HH:mm"); + +LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter); +String string = formatter.format(parsed); +System.out.println(string); // Nov 03, 2014 - 07:13 +``` + +Unlike `java.text.NumberFormat` the new `DateTimeFormatter` is immutable and **thread-safe**. + +For details on the pattern syntax read [here](http://download.java.net/jdk8/docs/api/java/time/format/DateTimeFormatter.html). + + +## Annotations + +Annotations in Java 8 are repeatable. Let's dive directly into an example to figure that out. + +First, we define a wrapper annotation which holds an array of the actual annotations: + +```java +@interface Hints { + Hint[] value(); +} + +@Repeatable(Hints.class) +@interface Hint { + String value(); +} +``` +Java 8 enables us to use multiple annotations of the same type by declaring the annotation `@Repeatable`. + +### Variant 1: Using the container annotation (old school) + +```java +@Hints({@Hint("hint1"), @Hint("hint2")}) +class Person {} +``` + +### Variant 2: Using repeatable annotations (new school) + +```java +@Hint("hint1") +@Hint("hint2") +class Person {} +``` + +Using variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation informations via reflection. + +```java +Hint hint = Person.class.getAnnotation(Hint.class); +System.out.println(hint); // null + +Hints hints1 = Person.class.getAnnotation(Hints.class); +System.out.println(hints1.value().length); // 2 + +Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); +System.out.println(hints2.length); // 2 +``` + +Although 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. + + +Furthermore the usage of annotations in Java 8 is expanded to two new targets: + +```java +@Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) +@interface MyAnnotation {} +``` + +## Where to go from here? + +My 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, just read my [follow up article](/posts/2014/03/29/jdk8-api-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. + +I've published a bunch of follow-up articles on my [blog](http://winterbe.com) that might be interesting to you: -- [Java 8 Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) - [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/) - [Java 8 Concurrency Tutorial: Threads and Executors](http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/) @@ -13,11 +760,3 @@ This repository contains all code samples from the Java 8 related posts of my [b - [Avoid Null Checks in Java 8](http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/) - [Fixing Java 8 Stream Gotchas with IntelliJ IDEA](http://winterbe.com/posts/2015/03/05/fixing-java-8-stream-gotchas-with-intellij-idea/) - [Using Backbone.js with Java 8 Nashorn](http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/) - -I'm adding new samples from time to time. - - -Contribute -============== - -Want to share your own java 8 code samples? Feel free to fork the repo and send me a pull request. From b49755311d196c1c3e8aac9f54093dfb3249a4a9 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 09:41:37 +0100 Subject: [PATCH 03/35] Table of Contents --- README.md | 41 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8a3d73fc..b34dfcd0 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,44 @@ Welcome 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! -This article was originally posted on my [blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). +This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). + +## Table of Contents + +* [Default Methods for Interfaces](#default-methods-for-interfaces) +* [Lambda expressions](#lambda-expressions) +* [Functional Interfaces](#functional-interfaces) +* [Method and Constructor References](#method-and-constructor-references) +* [Lambda Scopes](#lambda-scopes) + * [Accessing local variables](#accessing-local-variables) + * [Accessing fields and static variables](#accessing-fields-and-static-variables) + * [Accessing Default Interface Methods](#accessing-default-interface-methods) +* [Built-in Functional Interfaces](#built-in-functional-interfaces) + * [Predicates](#predicates) + * [Functions](#functions) + * [Suppliers](#suppliers) + * [Consumers](#consumers) + * [Comparators](#comparators) +** [Optionals](#optionals) +* [Streams](#streams) + * [Filter](#filter) + * [Sorted](#sorted) + * [Map](#map) + * [Match](#match) + * [Count](#count) + * [Reduce](#reduce) +* [Parallel Streams](#parallel-streams) + * [Sequential Sort](#sequential-sort) + * [Parallel Sort](#parallel-sort) +* [Maps](#maps) +* [Date API](#date-api) + * [Clock](#clock) + * [Timezones](#timezones) + * [LocalTime](#localtime) + * [LocalDate](#localdate) + * [LocalDateTime](#localdatetime) +* [Annotations](#annotations) +* [Where to go from here](#where-to-go-from-here) ## Default Methods for Interfaces @@ -492,7 +529,7 @@ System.out.println(String.format("parallel sort took: %d ms", millis)); As 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()`. -## Map +## Maps As already mentioned maps don't support streams. Instead maps now support various new and useful methods for doing common tasks. From 0bc23c5c633f58c5c6f0d3f9d1c02ef5d11d47cd Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 09:42:23 +0100 Subject: [PATCH 04/35] Fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b34dfcd0..4fea84b9 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ This article was originally posted on [my blog](http://winterbe.com/posts/2014/0 * [Suppliers](#suppliers) * [Consumers](#consumers) * [Comparators](#comparators) -** [Optionals](#optionals) +* [Optionals](#optionals) * [Streams](#streams) * [Filter](#filter) * [Sorted](#sorted) @@ -335,7 +335,7 @@ comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // < 0 ``` -### Optionals +## Optionals Optionals are not functional interfaces, instead it's a nifty utility to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work. From e08a3447f8f4e6299bb6a56dbc05fcf4c01085b0 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 09:44:48 +0100 Subject: [PATCH 05/35] Add Stream.js link --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 4fea84b9..8359b4e8 100644 --- a/README.md +++ b/README.md @@ -355,6 +355,8 @@ optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" A `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 sequential or parallel. +> You should also check out [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API. + Let's first look how sequential streams work. First we create a sample source in form of a list of strings: ```java From bf86aa19d4d55239d53359cbcf80551b93c13f02 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 09:53:10 +0100 Subject: [PATCH 06/35] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8359b4e8..9193b585 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > [“Java is still not dead—and people are starting to figure that out.”](https://twitter.com/mreinhold/status/429603588525281280) -Welcome 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! +Welcome 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!** This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). @@ -41,7 +41,7 @@ This article was originally posted on [my blog](http://winterbe.com/posts/2014/0 * [LocalDate](#localdate) * [LocalDateTime](#localdatetime) * [Annotations](#annotations) -* [Where to go from here](#where-to-go-from-here) +* [Where to go from here?](#where-to-go-from-here) ## Default Methods for Interfaces From 7fa21e257de5961ef4cac107be530a78395c73ae Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 10:34:05 +0100 Subject: [PATCH 07/35] Fix link --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9193b585..4826f5ab 100644 --- a/README.md +++ b/README.md @@ -786,9 +786,9 @@ Furthermore the usage of annotations in Java 8 is expanded to two new targets: ## Where to go from here? -My 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, just read my [follow up article](/posts/2014/03/29/jdk8-api-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. +My 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. -I've published a bunch of follow-up articles on my [blog](http://winterbe.com) that might be interesting to you: +I've also published a bunch of follow-up articles on my [blog](http://winterbe.com) that might be interesting to you: - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) - [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/) From 6afcb082a58de258a6e368e7a63d8a1cb65053ab Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 13:48:11 +0100 Subject: [PATCH 08/35] Use List.sort instead of Collections.sort --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4826f5ab..f7385411 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ Collections.sort(names, (String a, String b) -> b.compareTo(a)); For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even more shorter: ```java -Collections.sort(names, (a, b) -> b.compareTo(a)); +names.sort((a, b) -> b.compareTo(a)); ``` 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. From 82d57cd7c45d3774d545ee0cdfbf9811e25aaad3 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 13:49:05 +0100 Subject: [PATCH 09/35] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f7385411..288eadae 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ For one line method bodies you can skip both the braces `{}` and the `return` ke names.sort((a, b) -> b.compareTo(a)); ``` -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. +List now has a `sort` method. Alsot he 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. ## Functional Interfaces From c7d3ecf16ae1187a50b530f32594d08e85041148 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 13:49:29 +0100 Subject: [PATCH 10/35] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 288eadae..4600b64e 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ For one line method bodies you can skip both the braces `{}` and the `return` ke names.sort((a, b) -> b.compareTo(a)); ``` -List now has a `sort` method. Alsot he 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. +List 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. ## Functional Interfaces From 150f70f2d03372fb66138cfca0e2b92855ff8d93 Mon Sep 17 00:00:00 2001 From: aidendeom Date: Thu, 12 Nov 2015 13:25:00 -0500 Subject: [PATCH 11/35] Fix typo in README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4600b64e..79095927 100644 --- a/README.md +++ b/README.md @@ -563,7 +563,7 @@ map.computeIfAbsent(3, num -> "bam"); map.get(3); // val33 ``` -Next, we learn how to remove entries for a a given key, only if it's currently mapped to a given value: +Next, we learn how to remove entries for a given key, only if it's currently mapped to a given value: ```java map.remove(3, "val3"); From 3a2d67fc24cbc4ad66e0d1f06e083a98296c14ac Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 13 Nov 2015 07:29:36 +0100 Subject: [PATCH 12/35] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 79095927..1fa1967b 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Welcome 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!** -This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). +This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). You should [follow me on Twitter](https://twitter.com/winterbe_). ## Table of Contents @@ -799,3 +799,5 @@ I've also published a bunch of follow-up articles on my [blog](http://winterbe.c - [Avoid Null Checks in Java 8](http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/) - [Fixing Java 8 Stream Gotchas with IntelliJ IDEA](http://winterbe.com/posts/2015/03/05/fixing-java-8-stream-gotchas-with-intellij-idea/) - [Using Backbone.js with Java 8 Nashorn](http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/) + +You should [follow me on Twitter](https://twitter.com/winterbe_). Thanks for reading! From e0b308acf1e1977328d8871f7978f2879845ce4d Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 13 Nov 2015 07:46:41 +0100 Subject: [PATCH 13/35] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1fa1967b..a7755cb4 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,9 @@ This article was originally posted on [my blog](http://winterbe.com/posts/2014/0 ## Default Methods for Interfaces -Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the `default` keyword. This feature is also known as **Extension Methods**. Here is our first example: +Java 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). + +Here is our first example: ```java interface Formula { From 17ad55b5fb7eda2e03b2eae77e15dd1f95414261 Mon Sep 17 00:00:00 2001 From: thefourtheye Date: Fri, 13 Nov 2015 22:39:05 +0530 Subject: [PATCH 14/35] Fix typos and improve simple grammatical stuff --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index a7755cb4..a657328f 100644 --- a/README.md +++ b/README.md @@ -73,7 +73,7 @@ formula.calculate(100); // 100.0 formula.sqrt(16); // 4.0 ``` -The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calucation 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. +The 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. ## Lambda expressions @@ -118,7 +118,7 @@ List now has a `sort` method. Also the java compiler is aware of the parameter t ## Functional Interfaces -How does lambda expressions fit into Javas 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. +How 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. We 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. @@ -239,7 +239,7 @@ Writing to `num` from within the lambda expression is also prohibited. ### Accessing fields and static variables -In constrast 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. +In 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. ```java class Lambda4 { @@ -316,7 +316,7 @@ personSupplier.get(); // new Person ### Consumers -Consumers represents operations to be performed on a single input argument. +Consumers represent operations to be performed on a single input argument. ```java Consumer greeter = (p) -> System.out.println("Hello, " + p.firstName); @@ -339,7 +339,7 @@ comparator.reversed().compare(p1, p2); // < 0 ## Optionals -Optionals are not functional interfaces, instead it's a nifty utility to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work. +Optionals 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. Optional 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. @@ -355,7 +355,7 @@ optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" ## Streams -A `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 sequential or parallel. +A `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. > You should also check out [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API. @@ -482,7 +482,7 @@ reduced.ifPresent(System.out::println); ## Parallel Streams -As 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 concurrent on multiple threads. +As 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. The following example demonstrates how easy it is to increase the performance by using parallel streams. @@ -600,7 +600,7 @@ Java 8 contains a brand new date and time API under the package `java.time`. The ### Clock -Clock 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 milliseconds. 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. +Clock 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. ```java Clock clock = Clock.systemDefaultZone(); @@ -644,7 +644,7 @@ System.out.println(hoursBetween); // -3 System.out.println(minutesBetween); // -239 ``` -LocalTime comes with various factory method to simplify the creation of new instances, including parsing of time strings. +LocalTime comes with various factory methods to simplify the creation of new instances, including parsing of time strings. ```java LocalTime late = LocalTime.of(23, 59, 59); @@ -763,7 +763,7 @@ class Person {} class Person {} ``` -Using variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation informations via reflection. +Using variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation information via reflection. ```java Hint hint = Person.class.getAnnotation(Hint.class); From 928b82471ed20a6696140d1493d16170baf5f922 Mon Sep 17 00:00:00 2001 From: Robert Theis Date: Fri, 13 Nov 2015 18:20:40 -0800 Subject: [PATCH 15/35] Fixed spelling --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a657328f..c3dfce1d 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,7 @@ Integer converted = converter.convert("123"); System.out.println(converted); // 123 ``` -Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be ommited. +Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be omitted. ## Method and Constructor References From 870e1b11ca5b05ddf7bee67d828f92fc5627dab1 Mon Sep 17 00:00:00 2001 From: Chase Benson Date: Sat, 14 Nov 2015 15:10:33 -0500 Subject: [PATCH 16/35] Readme Typo Fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c3dfce1d..475008c0 100644 --- a/README.md +++ b/README.md @@ -661,7 +661,7 @@ System.out.println(leetTime); // 13:37 ### LocalDate -LocalDate 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 substracting days, months or years. Keep in mind that each manipulation returns a new instance. +LocalDate 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. ```java LocalDate today = LocalDate.now(); From eca818f92634e0a079ee9c310c49d650572b4035 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Mon, 16 Nov 2015 14:11:26 +0100 Subject: [PATCH 17/35] Improve description about streaming maps --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 475008c0..360a48ba 100644 --- a/README.md +++ b/README.md @@ -535,7 +535,9 @@ As you can see both code snippets are almost identical but the parallel sort is ## Maps -As already mentioned maps don't support streams. Instead maps now support various new and useful methods for doing common tasks. +As 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()`. + +Furthermore maps support various new and useful methods for doing common tasks. ```java Map map = new HashMap<>(); From 995fc00ec5e09f909d508c92a7302461cb13c290 Mon Sep 17 00:00:00 2001 From: Eran Medan Date: Mon, 16 Nov 2015 11:01:09 -0500 Subject: [PATCH 18/35] just a tiny grammar thing --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 360a48ba..badb54a8 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ As you can see the code is much shorter and easier to read. But it gets even sho Collections.sort(names, (String a, String b) -> b.compareTo(a)); ``` -For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even more shorter: +For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even shorter: ```java names.sort((a, b) -> b.compareTo(a)); From 97e248905f238c32bef3779f425274fbd1b969a0 Mon Sep 17 00:00:00 2001 From: grijesh Date: Fri, 20 Nov 2015 01:25:32 +0530 Subject: [PATCH 19/35] BiConsumer Example --- .../java8/samples/lambda/Lambda5.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/com/winterbe/java8/samples/lambda/Lambda5.java diff --git a/src/com/winterbe/java8/samples/lambda/Lambda5.java b/src/com/winterbe/java8/samples/lambda/Lambda5.java new file mode 100644 index 00000000..68a311f4 --- /dev/null +++ b/src/com/winterbe/java8/samples/lambda/Lambda5.java @@ -0,0 +1,32 @@ +package com.winterbe.java8.samples.lambda; + +import java.util.HashMap; +import java.util.function.BiConsumer; + +/** + * Created by grijesh + */ +public class Lambda5 { + + //Pre-Defined Functional Interfaces + public static void main(String... args) { + + //BiConsumer Example + BiConsumer printKeyAndValue + = (key,value) -> System.out.println(key+"-"+value); + + printKeyAndValue.accept("One",1); + printKeyAndValue.accept("Two",2); + + System.out.println("##################"); + + //Java Hash-Map foreach supports BiConsumer + HashMap dummyValues = new HashMap<>(); + dummyValues.put("One", 1); + dummyValues.put("Two", 2); + dummyValues.put("Three", 3); + + dummyValues.forEach((key,value) -> System.out.println(key+"-"+value)); + + } +} From d6c972191da3f22531e59fb8775e870f9cf15994 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 18 Dec 2015 11:18:52 +0100 Subject: [PATCH 20/35] Fix link #20 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index badb54a8..99ac9a48 100644 --- a/README.md +++ b/README.md @@ -729,7 +729,7 @@ System.out.println(string); // Nov 03, 2014 - 07:13 Unlike `java.text.NumberFormat` the new `DateTimeFormatter` is immutable and **thread-safe**. -For details on the pattern syntax read [here](http://download.java.net/jdk8/docs/api/java/time/format/DateTimeFormatter.html). +For details on the pattern syntax read [here](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html). ## Annotations From 3d878f673337ee05bd3cd3b98d3389b47783997e Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 5 Jan 2016 09:22:45 +0100 Subject: [PATCH 21/35] Happy new year 2016 --- LICENSE | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/LICENSE b/LICENSE index 3e09223f..58e794c6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014 Benjamin Winterberg +Copyright (c) 2016 Benjamin Winterberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. From ab7e2d2cc09fcb357701fe5d5ee4067ae2c542c6 Mon Sep 17 00:00:00 2001 From: Aiden Scandella Date: Wed, 13 Jan 2016 17:17:57 -0800 Subject: [PATCH 22/35] Fix whitespace in Default Interface Methods --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 99ac9a48..7ee572f3 100644 --- a/README.md +++ b/README.md @@ -267,7 +267,7 @@ Remember the formula example from the first section? Interface `Formula` defines Default methods **cannot** be accessed from within lambda expressions. The following code does not compile: ```java -Formula formula = (a) -> sqrt( a * 100); +Formula formula = (a) -> sqrt(a * 100); ``` From 6dd0e09f79cb53fdfa11851ec2afbf0c1664c20c Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 22 Mar 2016 11:37:08 +0100 Subject: [PATCH 23/35] Add link to stream tutorial --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ee572f3..ad01eb89 100644 --- a/README.md +++ b/README.md @@ -357,7 +357,7 @@ optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" A `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. -> You should also check out [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API. +> 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 [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API. Let's first look how sequential streams work. First we create a sample source in form of a list of strings: From 642ce1c298acbd637aa3375084eb7a105881daeb Mon Sep 17 00:00:00 2001 From: Sven Boekhoff Date: Tue, 5 Jul 2016 16:32:56 +0200 Subject: [PATCH 24/35] Use class instead of bean. A class should only be called 'bean', if: * all properties are private (use getters/setters) * it implements the Serializable interface * it has a public default constructor See: http://stackoverflow.com/questions/3295496/what-is-a-javabean-exactly --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ad01eb89..656cbd77 100644 --- a/README.md +++ b/README.md @@ -167,7 +167,7 @@ String converted = converter.convert("Java"); System.out.println(converted); // "J" ``` -Let's see how the `::` keyword works for constructors. First we define an example bean with different constructors: +Let's see how the `::` keyword works for constructors. First we define an example class with different constructors: ```java class Person { From 23839f740ee1ec2025827452408de45f7bb6c754 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 6 Oct 2016 17:12:13 +0200 Subject: [PATCH 25/35] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 656cbd77..b673fccc 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,8 @@ Welcome to my introduction to [Java 8](https://jdk8.java.net/). This tutorial gu This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). You should [follow me on Twitter](https://twitter.com/winterbe_). +_If you like this project, please give me a star._ ★ + ## Table of Contents * [Default Methods for Interfaces](#default-methods-for-interfaces) From 85dae289bdc6903b651f35fe1010d387d78ff90f Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 6 Oct 2016 17:12:29 +0200 Subject: [PATCH 26/35] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b673fccc..0d5e4ac7 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ # Modern Java - A Guide to Java 8 +_If you like this project, please give me a star._ ★ + > [“Java is still not dead—and people are starting to figure that out.”](https://twitter.com/mreinhold/status/429603588525281280) Welcome 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!** This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). You should [follow me on Twitter](https://twitter.com/winterbe_). -_If you like this project, please give me a star._ ★ - ## Table of Contents * [Default Methods for Interfaces](#default-methods-for-interfaces) From b2cbf4f9b7752861eebf295b2f30dd8ba43ab639 Mon Sep 17 00:00:00 2001 From: Steve Sun Date: Wed, 4 Jan 2017 20:02:05 -0800 Subject: [PATCH 27/35] update License to 2017 --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index 58e794c6..d82fe930 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 Benjamin Winterberg +Copyright (c) 2017 Benjamin Winterberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 7a076614461b6ef48e765441616bad0ffb446daa Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Oct 2017 18:18:27 +0200 Subject: [PATCH 28/35] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 0d5e4ac7..d2ce7413 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ _If you like this project, please give me a star._ ★ Welcome 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!** -This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). You should [follow me on Twitter](https://twitter.com/winterbe_). +This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). You should **[follow me on Twitter](https://twitter.com/winterbe_)** and check out my new project **[Sequency](https://github.com/winterbe/sequency)**. ## Table of Contents @@ -359,7 +359,7 @@ optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b" A `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. -> 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 [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API. +> 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.** Let's first look how sequential streams work. First we create a sample source in form of a list of strings: From 6ec91e6992e56b765b2ae2bcbf02733817acb844 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Oct 2017 18:30:02 +0200 Subject: [PATCH 29/35] Update README.md --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d2ce7413..08976bf0 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,17 @@ # Modern Java - A Guide to Java 8 - -_If you like this project, please give me a star._ ★ +_This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/)._ > [“Java is still not dead—and people are starting to figure that out.”](https://twitter.com/mreinhold/status/429603588525281280) Welcome 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!** -This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). You should **[follow me on Twitter](https://twitter.com/winterbe_)** and check out my new project **[Sequency](https://github.com/winterbe/sequency)**. +--- + +

+ ★★★ Like this project? Leave a star, follow on Twitter and check out my new project Sequency. Thanks! ★★★ +

+ +--- ## Table of Contents From 093d9a4af387eb4b713bfcb14c1baa686c27ac05 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 9 Jan 2018 10:04:59 +0100 Subject: [PATCH 30/35] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 08976bf0..10b63eeb 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ Welcome to my introduction to [Java 8](https://jdk8.java.net/). This tutorial gu ---

- ★★★ Like this project? Leave a star, follow on Twitter and check out my new project Sequency. Thanks! ★★★ + ★★★ Like this project? Leave a star, follow on Twitter or donate to support my work. Thanks! ★★★

--- From 81a0fa3aa1d6ec2409e0226d3a6c2f5c2d19a41d Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 4 Sep 2018 17:45:02 +0200 Subject: [PATCH 31/35] Java 11 local variable samples --- .../winterbe/java11/LocalVariableSyntax.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/com/winterbe/java11/LocalVariableSyntax.java diff --git a/src/com/winterbe/java11/LocalVariableSyntax.java b/src/com/winterbe/java11/LocalVariableSyntax.java new file mode 100644 index 00000000..e2a60906 --- /dev/null +++ b/src/com/winterbe/java11/LocalVariableSyntax.java @@ -0,0 +1,37 @@ +package com.winterbe.java11; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +public class LocalVariableSyntax { + + public static void main(String[] args) { + var text = "Banana"; +// Incompatible types: +// text = 1; + + +// Cannot infer type: +// var a; +// var nothing = null; +// var bla = () -> System.out.println("Hallo"); +// var method = LocalVariableSyntax::someMethod; + + var list1 = new ArrayList<>(); // ArrayList + + var list2 = new ArrayList>>(); + + for (var current : list2) { + // current is of type: Map> + System.out.println(current); + } + + Predicate predicate1 = (@Deprecated var a) -> false; + + } + + void someMethod() {} + +} From 4b92b43d53298652446651f94254341614c7873f Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 5 Sep 2018 10:35:12 +0200 Subject: [PATCH 32/35] Java 11 HttpClient examples --- .../winterbe/java11/HttpClientExamples.java | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 src/com/winterbe/java11/HttpClientExamples.java diff --git a/src/com/winterbe/java11/HttpClientExamples.java b/src/com/winterbe/java11/HttpClientExamples.java new file mode 100644 index 00000000..23a9e53f --- /dev/null +++ b/src/com/winterbe/java11/HttpClientExamples.java @@ -0,0 +1,77 @@ +package com.winterbe.java11; + +import java.io.IOException; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +public class HttpClientExamples { + + public static void main(String[] args) throws IOException, InterruptedException { +// syncRequest(); +// asyncRequest(); +// postData(); + basicAuth(); + } + + private static void syncRequest() throws IOException, InterruptedException { + var client = HttpClient.newHttpClient(); + var request = HttpRequest.newBuilder() + .uri(URI.create("https://winterbe.com")) + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + System.out.println(response.body()); + } + + private static void asyncRequest() { + var client = HttpClient.newHttpClient(); + var request = HttpRequest.newBuilder() + .uri(URI.create("https://winterbe.com")) + .build(); + client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) + .thenApply(HttpResponse::body) + .thenAccept(System.out::println); + } + + private static void postData() throws IOException, InterruptedException { + var client = HttpClient.newHttpClient(); + var request = HttpRequest.newBuilder() + .uri(URI.create("https://postman-echo.com/post")) + .timeout(Duration.ofSeconds(30)) + .version(HttpClient.Version.HTTP_2) + .header("Content-Type", "text/plain") + .POST(HttpRequest.BodyPublishers.ofString("Hi there!")) + .build(); + var response = client.send(request, HttpResponse.BodyHandlers.ofString()); + System.out.println(response.statusCode()); // 200 + } + + private static void basicAuth() throws IOException, InterruptedException { + var client = HttpClient.newHttpClient(); + var request1 = HttpRequest.newBuilder() + .uri(URI.create("https://postman-echo.com/basic-auth")) + .build(); + var response1 = client.send(request1, HttpResponse.BodyHandlers.ofString()); + System.out.println(response1.statusCode()); // 401 + + var authClient = HttpClient + .newBuilder() + .authenticator(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication("postman", "password".toCharArray()); + } + }) + .build(); + var request2 = HttpRequest.newBuilder() + .uri(URI.create("https://postman-echo.com/basic-auth")) + .build(); + var response2 = authClient.send(request2, HttpResponse.BodyHandlers.ofString()); + System.out.println(response2.statusCode()); // 200 + } + +} From f2d7b5b2ccf0ebd132cbcf162156706788e28cc3 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 5 Sep 2018 16:42:20 +0200 Subject: [PATCH 33/35] More Java 11 examples --- .../winterbe/java11/HttpClientExamples.java | 7 +- src/com/winterbe/java11/Misc.java | 69 +++++++++++++++++++ src/com/winterbe/java11/dummy.txt | 1 + 3 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 src/com/winterbe/java11/Misc.java create mode 100644 src/com/winterbe/java11/dummy.txt diff --git a/src/com/winterbe/java11/HttpClientExamples.java b/src/com/winterbe/java11/HttpClientExamples.java index 23a9e53f..7342b1de 100644 --- a/src/com/winterbe/java11/HttpClientExamples.java +++ b/src/com/winterbe/java11/HttpClientExamples.java @@ -19,26 +19,25 @@ public static void main(String[] args) throws IOException, InterruptedException } private static void syncRequest() throws IOException, InterruptedException { - var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://winterbe.com")) .build(); + var client = HttpClient.newHttpClient(); HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); } private static void asyncRequest() { - var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://winterbe.com")) .build(); + var client = HttpClient.newHttpClient(); client.sendAsync(request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println); } private static void postData() throws IOException, InterruptedException { - var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://postman-echo.com/post")) .timeout(Duration.ofSeconds(30)) @@ -46,12 +45,14 @@ private static void postData() throws IOException, InterruptedException { .header("Content-Type", "text/plain") .POST(HttpRequest.BodyPublishers.ofString("Hi there!")) .build(); + var client = HttpClient.newHttpClient(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.statusCode()); // 200 } private static void basicAuth() throws IOException, InterruptedException { var client = HttpClient.newHttpClient(); + var request1 = HttpRequest.newBuilder() .uri(URI.create("https://postman-echo.com/basic-auth")) .build(); diff --git a/src/com/winterbe/java11/Misc.java b/src/com/winterbe/java11/Misc.java new file mode 100644 index 00000000..e343dec7 --- /dev/null +++ b/src/com/winterbe/java11/Misc.java @@ -0,0 +1,69 @@ +package com.winterbe.java11; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Misc { + + @Deprecated(forRemoval = true) + String foo; + + public static void main(String[] args) throws IOException { + collections(); + strings(); + optionals(); + inputStreams(); + streams(); + } + + private static void streams() { + System.out.println(Stream.ofNullable(null).count()); // 0 + System.out.println(Stream.of(1, 2, 3, 2, 1) + .dropWhile(n -> n < 3) + .collect(Collectors.toList())); // [3, 2, 1] + System.out.println(Stream.of(1, 2, 3, 2, 1) + .takeWhile(n -> n < 3) + .collect(Collectors.toList())); // [1, 2] + } + + private static void inputStreams() throws IOException { + var classLoader = ClassLoader.getSystemClassLoader(); + var inputStream = classLoader.getResourceAsStream("com/winterbe/java11/dummy.txt"); + var tempFile = File.createTempFile("dummy-copy", "txt"); + try (var outputStream = new FileOutputStream(tempFile)) { + inputStream.transferTo(outputStream); + } + System.out.println(tempFile.length()); + } + + private static void optionals() { + System.out.println(Optional.of("foo").orElseThrow()); // foo + System.out.println(Optional.ofNullable(null).or(() -> Optional.of("bar")).get()); // bar + System.out.println(Optional.of("foo").stream().count()); // 1 + } + + private static void strings() { + System.out.println(" ".isBlank()); + System.out.println(" Foo Bar ".strip()); // "Foo Bar" + System.out.println(" Foo Bar ".stripTrailing()); // " Foo Bar" + System.out.println(" Foo Bar ".stripLeading()); // "Foo Bar " + System.out.println("Java".repeat(3)); // "JavaJavaJava" + System.out.println("A\nB\nC".lines().count()); // 3 + } + + private static void collections() { + var list = List.of("A", "B", "C"); + var copy = List.copyOf(list); + System.out.println(list == copy); // true + + var map = Map.of("A", 1, "B", 2); + System.out.println(map); + } + +} diff --git a/src/com/winterbe/java11/dummy.txt b/src/com/winterbe/java11/dummy.txt new file mode 100644 index 00000000..5eced957 --- /dev/null +++ b/src/com/winterbe/java11/dummy.txt @@ -0,0 +1 @@ +Foobar \ No newline at end of file From faf9793524cd6956428fa5d79e7fdce3a3184b56 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 25 Sep 2018 09:38:27 +0200 Subject: [PATCH 34/35] Add link to Java 11 Tutorial --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 10b63eeb..e9caeed4 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # Modern Java - A Guide to Java 8 _This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/)._ -> [“Java is still not dead—and people are starting to figure that out.”](https://twitter.com/mreinhold/status/429603588525281280) +> **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).** Welcome 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!** From 9b79999be76274f0c11a5b1d4a4fff4e785dc774 Mon Sep 17 00:00:00 2001 From: winterbe Date: Thu, 27 Apr 2023 09:52:04 +0200 Subject: [PATCH 35/35] Update LICENSE --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index d82fe930..cc53a543 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2017 Benjamin Winterberg +Copyright (c) 2023 Benjamin Winterberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal