Full Code of winterbe/java8-tutorial for AI

master 9b79999be762 cached
82 files
137.6 KB
34.0k tokens
300 symbols
1 requests
Download .txt
Repository: winterbe/java8-tutorial
Branch: master
Commit: 9b79999be762
Files: 82
Total size: 137.6 KB

Directory structure:
gitextract_v1c0ly93/

├── .gitignore
├── LICENSE
├── README.md
├── res/
│   ├── nashorn1.js
│   ├── nashorn10.js
│   ├── nashorn2.js
│   ├── nashorn3.js
│   ├── nashorn4.js
│   ├── nashorn5.js
│   ├── nashorn6.js
│   ├── nashorn7.js
│   ├── nashorn8.js
│   └── nashorn9.js
└── src/
    └── com/
        └── winterbe/
            ├── java11/
            │   ├── HttpClientExamples.java
            │   ├── LocalVariableSyntax.java
            │   ├── Misc.java
            │   └── dummy.txt
            └── java8/
                └── samples/
                    ├── concurrent/
                    │   ├── Atomic1.java
                    │   ├── CompletableFuture1.java
                    │   ├── ConcurrentHashMap1.java
                    │   ├── ConcurrentUtils.java
                    │   ├── Executors1.java
                    │   ├── Executors2.java
                    │   ├── Executors3.java
                    │   ├── Lock1.java
                    │   ├── Lock2.java
                    │   ├── Lock3.java
                    │   ├── Lock4.java
                    │   ├── Lock5.java
                    │   ├── Lock6.java
                    │   ├── LongAccumulator1.java
                    │   ├── LongAdder1.java
                    │   ├── Semaphore1.java
                    │   ├── Semaphore2.java
                    │   ├── Synchronized1.java
                    │   ├── Synchronized2.java
                    │   └── Threads1.java
                    ├── lambda/
                    │   ├── Interface1.java
                    │   ├── Lambda1.java
                    │   ├── Lambda2.java
                    │   ├── Lambda3.java
                    │   ├── Lambda4.java
                    │   ├── Lambda5.java
                    │   └── Person.java
                    ├── misc/
                    │   ├── Annotations1.java
                    │   ├── CheckedFunctions.java
                    │   ├── Concurrency1.java
                    │   ├── Files1.java
                    │   ├── Maps1.java
                    │   ├── Math1.java
                    │   └── String1.java
                    ├── nashorn/
                    │   ├── Nashorn1.java
                    │   ├── Nashorn10.java
                    │   ├── Nashorn11.java
                    │   ├── Nashorn2.java
                    │   ├── Nashorn3.java
                    │   ├── Nashorn4.java
                    │   ├── Nashorn5.java
                    │   ├── Nashorn6.java
                    │   ├── Nashorn7.java
                    │   ├── Nashorn8.java
                    │   ├── Nashorn9.java
                    │   ├── Product.java
                    │   └── SuperRunner.java
                    ├── stream/
                    │   ├── Optional1.java
                    │   ├── Optional2.java
                    │   ├── Streams1.java
                    │   ├── Streams10.java
                    │   ├── Streams11.java
                    │   ├── Streams12.java
                    │   ├── Streams13.java
                    │   ├── Streams2.java
                    │   ├── Streams3.java
                    │   ├── Streams4.java
                    │   ├── Streams5.java
                    │   ├── Streams6.java
                    │   ├── Streams7.java
                    │   ├── Streams8.java
                    │   └── Streams9.java
                    └── time/
                        ├── LocalDate1.java
                        ├── LocalDateTime1.java
                        └── LocalTime1.java

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
.DS_Store
.idea
*.iml
out
/bin/


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

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
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
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.


================================================
FILE: README.md
================================================
# 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/)._

> **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!**

---

<p align="center">
 ★★★ Like this project? Leave a star, <a href="https://twitter.com/winterbe_">follow on Twitter</a> or <a href="https://www.paypal.me/winterbe">donate</a> to support my work. Thanks! ★★★
</p>

---

## 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

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 {
    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 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

Let's start with a simple example of how to sort a list of strings in prior versions of Java:

```java
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");

Collections.sort(names, new Comparator<String>() {
    @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 shorter:

```java
names.sort((a, b) -> b.compareTo(a));
```

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

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.

Example:

```java
@FunctionalInterface
interface Converter<F, T> {
    T convert(F from);
}
```

```java
Converter<String, Integer> 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 omitted.


## Method and Constructor References

The above example code can be further simplified by utilizing static method references:

```java
Converter<String, Integer> 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<String, String> 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 class 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 extends Person> {
    P create(String firstName, String lastName);
}
```

Instead of implementing the factory manually, we glue everything together via constructor references:

```java
PersonFactory<Person> 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<Integer, String> 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<Integer, String> 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<Integer, String> 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 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 {
    static int outerStaticNum;
    int outerNum;

    void testScopes() {
        Converter<Integer, String> stringConverter1 = (from) -> {
            outerNum = 23;
            return String.valueOf(from);
        };

        Converter<Integer, String> 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<String> predicate = (s) -> s.length() > 0;

predicate.test("foo");              // true
predicate.negate().test("foo");     // false

Predicate<Boolean> nonNull = Objects::nonNull;
Predicate<Boolean> isNull = Objects::isNull;

Predicate<String> isEmpty = String::isEmpty;
Predicate<String> 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<String, Integer> toInteger = Integer::valueOf;
Function<String, String> 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<Person> personSupplier = Person::new;
personSupplier.get();   // new Person
```

### Consumers

Consumers represent operations to be performed on a single input argument.

```java
Consumer<Person> 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<Person> 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, 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.

```java
Optional<String> 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 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 [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:

```java
List<String> 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<String> 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 concurrently 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<String> 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()`.

## Maps

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<Integer, String> 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 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 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();
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 methods 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 subtracting 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](https://docs.oracle.com/javase/8/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 information 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, 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 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/)
- [Java 8 Concurrency Tutorial: Threads and Executors](http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/)
- [Java 8 Concurrency Tutorial: Synchronization and Locks](http://winterbe.com/posts/2015/04/30/java8-concurrency-tutorial-synchronized-locks-examples/)
- [Java 8 Concurrency Tutorial: Atomic Variables and ConcurrentMap](http://winterbe.com/posts/2015/05/22/java8-concurrency-tutorial-atomic-concurrent-map-examples/)
- [Java 8 API by Example: Strings, Numbers, Math and Files](http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/)
- [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!


================================================
FILE: res/nashorn1.js
================================================
var fun1 = function(name) {
    print('Hi there from Javascript, ' + name);
    return "greetings from javascript";
};

var fun2 = function (object) {
    print("JS Class Definition: " + Object.prototype.toString.call(object));
};

================================================
FILE: res/nashorn10.js
================================================
var results = [];

var Context = function () {
    this.foo = 'bar';
};

Context.prototype.testArgs = function () {
    if (arguments[0]) {
        results.push(true);
    }
    if (arguments[1]) {
        results.push(true);
    }
    if (arguments[2]) {
        results.push(true);
    }
    if (arguments[3]) {
        results.push(true);
    }
};

var testPerf = function () {
    var context = new Context();
    context.testArgs();
    context.testArgs(1);
    context.testArgs(1, 2);
    context.testArgs(1, 2, 3);
    context.testArgs(1, 2, 3, 4);
};

================================================
FILE: res/nashorn2.js
================================================
var Nashorn2 = Java.type('com.winterbe.java8.samples.nashorn.Nashorn2');
var result = Nashorn2.fun('John Doe');
print('\n' + result);

Nashorn2.fun2(123);
Nashorn2.fun2(49.99);
Nashorn2.fun2(true);
Nashorn2.fun2("hi there")
Nashorn2.fun2(String("bam"))
Nashorn2.fun2(new Number(23));
Nashorn2.fun2(new Date());
Nashorn2.fun2(new RegExp());
Nashorn2.fun2({foo: 'bar'});


print('passing object hash:');
Nashorn2.fun3({
    foo: 'bar',
    bar: 'foo'
});


print('passing custom person object:');

function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.getFullName = function() {
        return this.firstName + " " + this.lastName;
    }
}

var person1 = new Person("Peter", "Parker");
Nashorn2.fun3(person1);
Nashorn2.fun4(person1);

================================================
FILE: res/nashorn3.js
================================================
print('------------------');
print('IntArray:');

var IntArray = Java.type('int[]');

var array = new IntArray(5);
array[0] = 5;
array[1] = 4;
array[2] = 3;
array[3] = 2;
array[4] = 1;

try {
    array[5] = 23;
} catch (e) {
    print(e.message);
}

array[0] = "17";
print(array[0]);

array[0] = "wrong type";
print(array[0]);

array[0] = "17.3";
print(array[0]);

print('------------------');

for (var i in array) print(i);

print('------------------');

for each (var val in array) print(val);

print('------------------');
print('ArrayList:');

var ArrayList = Java.type('java.util.ArrayList');

var list = new ArrayList();
list.add('a');
list.add('b');
list.add('c');

for each (var el in list) print(el);


print('------------------');
print('HashMap:');

var HashMap = Java.type('java.util.HashMap');

var map = new HashMap();
map.put('foo', 'foo1');
map.put('bar', 'bar1');

for each(var e in map.keySet()) print(e);

for each(var e in map.values()) print(e);


print('------------------');
print('Streams:');

var list2 = new ArrayList();
list2.add("ddd2");
list2.add("aaa2");
list2.add("bbb1");
list2.add("aaa1");
list2.add("bbb3");
list2.add("ccc");
list2.add("bbb2");
list2.add("ddd1");

list2
    .stream()
    .filter(function(el) {
        return el.startsWith("aaa");
    })
    .sorted()
    .forEach(function(el) {
        print(el);
    });



print('------------------');
print('Extend:');

var Runnable = Java.type('java.lang.Runnable');
var Printer = Java.extend(Runnable, {
    run: function() {
        print('This was printed from a seperate thread.');
    }
});

var Thread = Java.type('java.lang.Thread');
new Thread(new Printer()).start();

new Thread(function() {
    print('this was printed from another thread');
}).start();


print('------------------');
print('Parameter Overload:');

var System = Java.type('java.lang.System');

System.out.println(10);
System.out["println"](11.0);
System.out["println(double)"](12);

print('------------------');
print('JavaBeans:');

var Date = Java.type('java.util.Date');
var date = new Date();
date.year += 1900;
System.out.println(date.year);

================================================
FILE: res/nashorn4.js
================================================
// function literal with no braces

function sqr(x) x * x;

print(sqr(3));


// for each

var array = [1, 2, 3, 4];
for each (var num in array) print(num);


// object literals in constructors

var runnable = new java.lang.Runnable() {
    run: function() {
        print('on the run');
    }
};

runnable.run();


// bind properties

var o1 = {};
var o2 = { foo: 'bar'};

Object.bindProperties(o1, o2);

print(o1.foo);
o1.foo = 'BAM';
print(o2.foo);


// string trim

print("   hehe".trimLeft());
print("hehe    ".trimRight() + "he");


// whereis
print(__FILE__, __LINE__, __DIR__);


// java import

var imports = new JavaImporter(java.io, java.lang);
with (imports) {
    var file = new File(__FILE__);
    System.out.println(file.getAbsolutePath());
    // /path/to/my/script.js
}


// convert iterable to js array

var list = new java.util.ArrayList();
list.add("s1");
list.add("s2");
list.add("s3");

var jsArray = Java.from(list);
print(jsArray);
print(Object.prototype.toString.call(jsArray));


// convert js array to java array

var javaArray = Java.to([3, 5, 7, 11], "int[]");
print(Object.prototype.toString.call(javaArray));


// calling super

var SuperRunner = Java.type('com.winterbe.java8.samples.nashorn.SuperRunner');
var Runner = Java.extend(SuperRunner);

var runner = new Runner() {
    run: function() {
        Java.super(runner).run();
        print('on my run');
    }
}
runner.run();



// load

load('http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js');

var odds = _.filter([1, 2, 3, 4, 5, 6], function (num) {
    return num % 2 == 1;
});

print(odds);

================================================
FILE: res/nashorn5.js
================================================
function Product(name) {
    this.name = name;
}

Product.prototype.stock = 0;
Product.prototype.price = 0;
Product.prototype.getValueOfGoods = function() {
    return this.stock * this.price;
};

var product = new Product('Pencil');
product.price = 4.99;
product.stock = 78;

print('Value of Goods: ' + product.getValueOfGoods());


var getValueOfGoods = function(javaProduct) {
    var jsProduct = new Product();
    Object.bindProperties(jsProduct, javaProduct);
    return jsProduct.getValueOfGoods();
};

================================================
FILE: res/nashorn6.js
================================================
load('http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js');
load('http://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js');


// simple backbone model:
// valueOfGoods will automatically be calculated when stock or price changes
var Product = Backbone.Model.extend({
    defaults: {
        stock: 0,
        price: 0.0,
        name:'',
        valueOfGoods: 0.0
    },

    initialize: function() {
        this.on('change:stock change:price', function() {
            var stock = this.get('stock');
            var price = this.get('price');
            var valueOfGoods = this.getValueOfGoods(stock, price);
            this.set('valueOfGoods', valueOfGoods);
        });
    },

    getValueOfGoods: function(stock, price) {
        return stock * price;
    }
});

var product = new Product();
product.set('name', 'Pencil');
product.set('stock', 1000);
product.set('price', 3.99);


// pass backbone model to java method
var Nashorn6 = Java.type('com.winterbe.java8.samples.nashorn.Nashorn6');
Nashorn6.getProduct(product.attributes);


// bind java object to backbone model and pass result back to java
var calculate = function(javaProduct) {
    var model = new Product();
    model.set('name', javaProduct.name);
    model.set('price', javaProduct.price);
    model.set('stock', javaProduct.stock);
    return model.attributes;
};

================================================
FILE: res/nashorn7.js
================================================
function sqrt(x)  x * x
print(sqrt(3));

var array = [1, 2, 3, 4];
for each (var num in array) print(num);

var runnable = new java.lang.Runnable() {
    run: function () {
        print('on the run');
    }
};

runnable.run();

var System = Java.type('java.lang.System');
System.out["println(double)"](12);

var Arrays = Java.type("java.util.Arrays");
var javaArray = Java.to([2, 3, 7, 11, 14], "int[]");

Arrays.stream(javaArray)
    .filter(function (num) {
        return num % 2 === 1;
    })
    .forEach(function (num) {
        print(num);
    });

================================================
FILE: res/nashorn8.js
================================================
var evaluate1 = function () {
    (function () {
        print(eval("this"));
    }).call(this);
};

var evaluate2 = function () {
    var context = {};
    (function () {
        print(eval("this"));
    }).call(context);
};

var evaluate3 = function (context) {
    (function () {
        print(eval("this"));
    }).call(context);
};

================================================
FILE: res/nashorn9.js
================================================
var size = 100000;

var testPerf = function () {
    var result = Math.floor(Math.random() * size) + 1;
    for (var i = 0; i < size; i++) {
        result += i;
    }
    return result;
};

================================================
FILE: src/com/winterbe/java11/HttpClientExamples.java
================================================
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 request = HttpRequest.newBuilder()
                .uri(URI.create("https://winterbe.com"))
                .build();
        var client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }

    private static void asyncRequest() {
        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 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 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();
        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
    }

}


================================================
FILE: src/com/winterbe/java11/LocalVariableSyntax.java
================================================
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<Object>

        var list2 = new ArrayList<Map<String, List<Integer>>>();

        for (var current : list2) {
            // current is of type: Map<String, List<Integer>>
            System.out.println(current);
        }

        Predicate<String> predicate1 = (@Deprecated var a) -> false;

    }

    void someMethod() {}

}


================================================
FILE: src/com/winterbe/java11/Misc.java
================================================
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);
    }

}


================================================
FILE: src/com/winterbe/java11/dummy.txt
================================================
Foobar

================================================
FILE: src/com/winterbe/java8/samples/concurrent/Atomic1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Atomic1 {

    private static final int NUM_INCREMENTS = 1000;

    private static AtomicInteger atomicInt = new AtomicInteger(0);

    public static void main(String[] args) {
        testIncrement();
        testAccumulate();
        testUpdate();
    }

    private static void testUpdate() {
        atomicInt.set(0);

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> {
                    Runnable task = () ->
                            atomicInt.updateAndGet(n -> n + 2);
                    executor.submit(task);
                });

        ConcurrentUtils.stop(executor);

        System.out.format("Update: %d\n", atomicInt.get());
    }

    private static void testAccumulate() {
        atomicInt.set(0);

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> {
                    Runnable task = () ->
                            atomicInt.accumulateAndGet(i, (n, m) -> n + m);
                    executor.submit(task);
                });

        ConcurrentUtils.stop(executor);

        System.out.format("Accumulate: %d\n", atomicInt.get());
    }

    private static void testIncrement() {
        atomicInt.set(0);

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(atomicInt::incrementAndGet));

        ConcurrentUtils.stop(executor);

        System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, atomicInt.get());
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author Benjamin Winterberg
 */
public class CompletableFuture1 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = new CompletableFuture<>();

        future.complete("42");

        future
                .thenAccept(System.out::println)
                .thenAccept(v -> System.out.println("done"));

    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ForkJoinPool;

/**
 * @author Benjamin Winterberg
 */
public class ConcurrentHashMap1 {

    public static void main(String[] args) {
        System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism());

        testForEach();
        testSearch();
        testReduce();
    }

    private static void testReduce() {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
        map.putIfAbsent("foo", "bar");
        map.putIfAbsent("han", "solo");
        map.putIfAbsent("r2", "d2");
        map.putIfAbsent("c3", "p0");

        String reduced = map.reduce(1, (key, value) -> key + "=" + value,
                (s1, s2) -> s1 + ", " + s2);

        System.out.println(reduced);
    }

    private static void testSearch() {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
        map.putIfAbsent("foo", "bar");
        map.putIfAbsent("han", "solo");
        map.putIfAbsent("r2", "d2");
        map.putIfAbsent("c3", "p0");

        System.out.println("\nsearch()\n");

        String result1 = map.search(1, (key, value) -> {
            System.out.println(Thread.currentThread().getName());
            if (key.equals("foo") && value.equals("bar")) {
                return "foobar";
            }
            return null;
        });

        System.out.println(result1);

        System.out.println("\nsearchValues()\n");

        String result2 = map.searchValues(1, value -> {
            System.out.println(Thread.currentThread().getName());
            if (value.length() > 3) {
                return value;
            }
            return null;
        });

        System.out.println(result2);
    }

    private static void testForEach() {
        ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
        map.putIfAbsent("foo", "bar");
        map.putIfAbsent("han", "solo");
        map.putIfAbsent("r2", "d2");
        map.putIfAbsent("c3", "p0");

        map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));
//        map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName()));

        System.out.println(map.mappingCount());
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class ConcurrentUtils {

    public static void stop(ExecutorService executor) {
        try {
            executor.shutdown();
            executor.awaitTermination(60, TimeUnit.SECONDS);
        }
        catch (InterruptedException e) {
            System.err.println("termination interrupted");
        }
        finally {
            if (!executor.isTerminated()) {
                System.err.println("killing non-finished tasks");
            }
            executor.shutdownNow();
        }
    }

    public static void sleep(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Executors1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Executors1 {

    public static void main(String[] args) {
        test1(3);
//        test1(7);
    }

    private static void test1(long seconds) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(seconds);
                String name = Thread.currentThread().getName();
                System.out.println("task finished: " + name);
            }
            catch (InterruptedException e) {
                System.err.println("task interrupted");
            }
        });
        stop(executor);
    }

    static void stop(ExecutorService executor) {
        try {
            System.out.println("attempt to shutdown executor");
            executor.shutdown();
            executor.awaitTermination(5, TimeUnit.SECONDS);
        }
        catch (InterruptedException e) {
            System.err.println("termination interrupted");
        }
        finally {
            if (!executor.isTerminated()) {
                System.err.println("killing non-finished tasks");
            }
            executor.shutdownNow();
            System.out.println("shutdown finished");
        }
    }
}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Executors2.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author Benjamin Winterberg
 */
public class Executors2 {

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
//        test1();
//        test2();
        test3();
    }

    private static void test3() throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        Future<Integer> future = executor.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                return 123;
            }
            catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        });

        future.get(1, TimeUnit.SECONDS);
    }

    private static void test2() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        Future<Integer> future = executor.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                return 123;
            }
            catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        });

        executor.shutdownNow();
        future.get();
    }

    private static void test1() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        Future<Integer> future = executor.submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                return 123;
            }
            catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        });

        System.out.println("future done: " + future.isDone());

        Integer result = future.get();

        System.out.println("future done: " + future.isDone());
        System.out.print("result: " + result);

        executor.shutdownNow();
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Executors3.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Executors3 {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        test1();
//        test2();
//        test3();

//        test4();
//        test5();
    }

    private static void test5() throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newWorkStealingPool();

        List<Callable<String>> callables = Arrays.asList(
                callable("task1", 2),
                callable("task2", 1),
                callable("task3", 3));

        String result = executor.invokeAny(callables);
        System.out.println(result);

        executor.shutdown();
    }

    private static Callable<String> callable(String result, long sleepSeconds) {
        return () -> {
            TimeUnit.SECONDS.sleep(sleepSeconds);
            return result;
        };
    }

    private static void test4() throws InterruptedException {
        ExecutorService executor = Executors.newWorkStealingPool();

        List<Callable<String>> callables = Arrays.asList(
                () -> "task1",
                () -> "task2",
                () -> "task3");

        executor.invokeAll(callables)
                .stream()
                .map(future -> {
                    try {
                        return future.get();
                    }
                    catch (Exception e) {
                        throw new IllegalStateException(e);
                    }
                })
                .forEach(System.out::println);

        executor.shutdown();
    }

    private static void test3() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable task = () -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                System.out.println("Scheduling: " + System.nanoTime());
            }
            catch (InterruptedException e) {
                System.err.println("task interrupted");
            }
        };

        executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS);
    }

    private static void test2() {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
        int initialDelay = 0;
        int period = 1;
        executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
    }

    private static void test1() throws InterruptedException {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

        Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
        int delay = 3;
        ScheduledFuture<?> future = executor.schedule(task, delay, TimeUnit.SECONDS);

        TimeUnit.MILLISECONDS.sleep(1337);

        long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
        System.out.printf("Remaining Delay: %sms\n", remainingDelay);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Lock1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Lock1 {

    private static final int NUM_INCREMENTS = 10000;

    private static ReentrantLock lock = new ReentrantLock();

    private static int count = 0;

    private static void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        testLock();
    }

    private static void testLock() {
        count = 0;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                 .forEach(i -> executor.submit(Lock1::increment));

        ConcurrentUtils.stop(executor);

        System.out.println(count);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Lock2.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Benjamin Winterberg
 */
public class Lock2 {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        ReentrantLock lock = new ReentrantLock();

        executor.submit(() -> {
            lock.lock();
            try {
                ConcurrentUtils.sleep(1);
            } finally {
                lock.unlock();
            }
        });

        executor.submit(() -> {
            System.out.println("Locked: " + lock.isLocked());
            System.out.println("Held by me: " + lock.isHeldByCurrentThread());
            boolean locked = lock.tryLock();
            System.out.println("Lock acquired: " + locked);
        });

        ConcurrentUtils.stop(executor);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Lock3.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author Benjamin Winterberg
 */
public class Lock3 {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Map<String, String> map = new HashMap<>();

        ReadWriteLock lock = new ReentrantReadWriteLock();

        executor.submit(() -> {
            lock.writeLock().lock();
            try {
                ConcurrentUtils.sleep(1);
                map.put("foo", "bar");
            } finally {
                lock.writeLock().unlock();
            }
        });

        Runnable readTask = () -> {
            lock.readLock().lock();
            try {
                System.out.println(map.get("foo"));
                ConcurrentUtils.sleep(1);
            } finally {
                lock.readLock().unlock();
            }
        };
        executor.submit(readTask);
        executor.submit(readTask);

        ConcurrentUtils.stop(executor);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Lock4.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;

/**
 * @author Benjamin Winterberg
 */
public class Lock4 {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        Map<String, String> map = new HashMap<>();

        StampedLock lock = new StampedLock();

        executor.submit(() -> {
            long stamp = lock.writeLock();
            try {
                ConcurrentUtils.sleep(1);
                map.put("foo", "bar");
            } finally {
                lock.unlockWrite(stamp);
            }
        });

        Runnable readTask = () -> {
            long stamp = lock.readLock();
            try {
                System.out.println(map.get("foo"));
                ConcurrentUtils.sleep(1);
            } finally {
                lock.unlockRead(stamp);
            }
        };
        executor.submit(readTask);
        executor.submit(readTask);

        ConcurrentUtils.stop(executor);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Lock5.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;

/**
 * @author Benjamin Winterberg
 */
public class Lock5 {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        StampedLock lock = new StampedLock();

        executor.submit(() -> {
            long stamp = lock.tryOptimisticRead();
            try {
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
                ConcurrentUtils.sleep(1);
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
                ConcurrentUtils.sleep(2);
                System.out.println("Optimistic Lock Valid: " + lock.validate(stamp));
            } finally {
                lock.unlock(stamp);
            }
        });

        executor.submit(() -> {
            long stamp = lock.writeLock();
            try {
                System.out.println("Write Lock acquired");
                ConcurrentUtils.sleep(2);
            } finally {
                lock.unlock(stamp);
                System.out.println("Write done");
            }
        });

        ConcurrentUtils.stop(executor);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Lock6.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.StampedLock;

/**
 * @author Benjamin Winterberg
 */
public class Lock6 {

    private static int count = 0;

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        StampedLock lock = new StampedLock();

        executor.submit(() -> {
            long stamp = lock.readLock();
            try {
                if (count == 0) {
                    stamp = lock.tryConvertToWriteLock(stamp);
                    if (stamp == 0L) {
                        System.out.println("Could not convert to write lock");
                        stamp = lock.writeLock();
                    }
                    count = 23;
                }
                System.out.println(count);
            } finally {
                lock.unlock(stamp);
            }
        });

        ConcurrentUtils.stop(executor);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAccumulator;
import java.util.function.LongBinaryOperator;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class LongAccumulator1 {

    public static void main(String[] args) {
        testAccumulate();
    }

    private static void testAccumulate() {
        LongBinaryOperator op = (x, y) -> 2 * x + y;
        LongAccumulator accumulator = new LongAccumulator(op, 1L);

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, 10)
                .forEach(i -> executor.submit(() -> accumulator.accumulate(i)));

        ConcurrentUtils.stop(executor);

        System.out.format("Add: %d\n", accumulator.getThenReset());
    }
}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/LongAdder1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class LongAdder1 {

    private static final int NUM_INCREMENTS = 10000;

    private static LongAdder adder = new LongAdder();

    public static void main(String[] args) {
        testIncrement();
        testAdd();
    }

    private static void testAdd() {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(() -> adder.add(2)));

        ConcurrentUtils.stop(executor);

        System.out.format("Add: %d\n", adder.sumThenReset());
    }

    private static void testIncrement() {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(adder::increment));

        ConcurrentUtils.stop(executor);

        System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, adder.sumThenReset());
    }
}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Semaphore1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Semaphore1 {

    private static final int NUM_INCREMENTS = 10000;

    private static Semaphore semaphore = new Semaphore(1);

    private static int count = 0;

    public static void main(String[] args) {
        testIncrement();
    }

    private static void testIncrement() {
        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(Semaphore1::increment));

        ConcurrentUtils.stop(executor);

        System.out.println("Increment: " + count);
    }

    private static void increment() {
        boolean permit = false;
        try {
            permit = semaphore.tryAcquire(5, TimeUnit.SECONDS);
            count++;
        }
        catch (InterruptedException e) {
            throw new RuntimeException("could not increment");
        }
        finally {
            if (permit) {
                semaphore.release();
            }
        }
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Semaphore2.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Semaphore2 {

    private static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(10);

        IntStream.range(0, 10)
                .forEach(i -> executor.submit(Semaphore2::doWork));

        ConcurrentUtils.stop(executor);
    }

    private static void doWork() {
        boolean permit = false;
        try {
            permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);
            if (permit) {
                System.out.println("Semaphore acquired");
                ConcurrentUtils.sleep(5);
            } else {
                System.out.println("Could not acquire semaphore");
            }
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        } finally {
            if (permit) {
                semaphore.release();
            }
        }
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Synchronized1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Synchronized1 {

    private static final int NUM_INCREMENTS = 10000;

    private static int count = 0;

    public static void main(String[] args) {
        testSyncIncrement();
        testNonSyncIncrement();
    }

    private static void testSyncIncrement() {
        count = 0;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(Synchronized1::incrementSync));

        ConcurrentUtils.stop(executor);

        System.out.println("   Sync: " + count);
    }

    private static void testNonSyncIncrement() {
        count = 0;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(Synchronized1::increment));

        ConcurrentUtils.stop(executor);

        System.out.println("NonSync: " + count);
    }

    private static synchronized void incrementSync() {
        count = count + 1;
    }

    private static void increment() {
        count = count + 1;
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Synchronized2.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Synchronized2 {

    private static final int NUM_INCREMENTS = 10000;

    private static int count = 0;

    public static void main(String[] args) {
        testSyncIncrement();
    }

    private static void testSyncIncrement() {
        count = 0;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(Synchronized2::incrementSync));

        ConcurrentUtils.stop(executor);

        System.out.println(count);
    }

    private static void incrementSync() {
        synchronized (Synchronized2.class) {
            count = count + 1;
        }
    }

}


================================================
FILE: src/com/winterbe/java8/samples/concurrent/Threads1.java
================================================
package com.winterbe.java8.samples.concurrent;

import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Threads1 {

    public static void main(String[] args) {
        test1();
//        test2();
//        test3();
    }

    private static void test3() {
        Runnable runnable = () -> {
            try {
                System.out.println("Foo " + Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(1);
                System.out.println("Bar " + Thread.currentThread().getName());
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
    }

    private static void test2() {
        Runnable runnable = () -> {
            try {
                System.out.println("Foo " + Thread.currentThread().getName());
                Thread.sleep(1000);
                System.out.println("Bar " + Thread.currentThread().getName());
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
    }

    private static void test1() {
        Runnable runnable = () -> {
            String threadName = Thread.currentThread().getName();
            System.out.println("Hello " + threadName);
        };

        runnable.run();

        Thread thread = new Thread(runnable);
        thread.start();

        System.out.println("Done!");
    }
}


================================================
FILE: src/com/winterbe/java8/samples/lambda/Interface1.java
================================================
package com.winterbe.java8.samples.lambda;

/**
 * @author Benjamin Winterberg
 */
public class Interface1 {

    interface Formula {
        double calculate(int a);

        default double sqrt(int a) {
            return Math.sqrt(positive(a));
        }

        static int positive(int a) {
            return a > 0 ? a : 0;
        }
    }

    public static void main(String[] args) {
        Formula formula1 = new Formula() {
            @Override
            public double calculate(int a) {
                return sqrt(a * 100);
            }
        };

        formula1.calculate(100);     // 100.0
        formula1.sqrt(-23);          // 0.0
        Formula.positive(-4);        // 0.0

//        Formula formula2 = (a) -> sqrt( a * 100);
    }

}

================================================
FILE: src/com/winterbe/java8/samples/lambda/Lambda1.java
================================================
package com.winterbe.java8.samples.lambda;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 * @author Benjamin Winterberg
 */
public class Lambda1 {

    public static void main(String[] args) {
        List<String> names = Arrays.asList("peter", "anna", "mike", "xenia");

        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String a, String b) {
                return b.compareTo(a);
            }
        });

        Collections.sort(names, (String a, String b) -> {
            return b.compareTo(a);
        });

        Collections.sort(names, (String a, String b) -> b.compareTo(a));

        Collections.sort(names, (a, b) -> b.compareTo(a));

        System.out.println(names);

        names.sort(Collections.reverseOrder());

        System.out.println(names);

        List<String> names2 = Arrays.asList("peter", null, "anna", "mike", "xenia");
        names2.sort(Comparator.nullsLast(String::compareTo));
        System.out.println(names2);

        List<String> names3 = null;

        Optional.ofNullable(names3).ifPresent(list -> list.sort(Comparator.naturalOrder()));

        System.out.println(names3);
    }

}

================================================
FILE: src/com/winterbe/java8/samples/lambda/Lambda2.java
================================================
package com.winterbe.java8.samples.lambda;

/**
 * @author Benjamin Winterberg
 */
public class Lambda2 {

    @FunctionalInterface
    public static interface Converter<F, T> {
        T convert(F from);
    }

    static class Something {
        String startsWith(String s) {
            return String.valueOf(s.charAt(0));
        }
    }

    interface PersonFactory<P extends Person> {
        P create(String firstName, String lastName);
    }

    public static void main(String[] args) {
        Converter<String, Integer> integerConverter1 = (from) -> Integer.valueOf(from);
        Integer converted1 = integerConverter1.convert("123");
        System.out.println(converted1);   // result: 123


        // method reference

        Converter<String, Integer> integerConverter2 = Integer::valueOf;
        Integer converted2 = integerConverter2.convert("123");
        System.out.println(converted2);   // result: 123


        Something something = new Something();

        Converter<String, String> stringConverter = something::startsWith;
        String converted3 = stringConverter.convert("Java");
        System.out.println(converted3);    // result J

        // constructor reference

        PersonFactory<Person> personFactory = Person::new;
        Person person = personFactory.create("Peter", "Parker");
    }
}


================================================
FILE: src/com/winterbe/java8/samples/lambda/Lambda3.java
================================================
package com.winterbe.java8.samples.lambda;

import java.util.Comparator;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * Common standard functions from the Java API.
 *
 * @author Benjamin Winterberg
 */
public class Lambda3 {

    @FunctionalInterface
    interface Fun {
        void foo();
    }

    public static void main(String[] args) throws Exception {

        // Predicates

        Predicate<String> predicate = (s) -> s.length() > 0;

        predicate.test("foo");              // true
        predicate.negate().test("foo");     // false

        Predicate<Boolean> nonNull = Objects::nonNull;
        Predicate<Boolean> isNull = Objects::isNull;

        Predicate<String> isEmpty = String::isEmpty;
        Predicate<String> isNotEmpty = isEmpty.negate();


        // Functions

        Function<String, Integer> toInteger = Integer::valueOf;
        Function<String, String> backToString = toInteger.andThen(String::valueOf);

        backToString.apply("123");     // "123"


        // Suppliers

        Supplier<Person> personSupplier = Person::new;
        personSupplier.get();   // new Person


        // Consumers

        Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
        greeter.accept(new Person("Luke", "Skywalker"));



        // Comparators

        Comparator<Person> 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


        // Runnables

        Runnable runnable = () -> System.out.println(UUID.randomUUID());
        runnable.run();


        // Callables

        Callable<UUID> callable = UUID::randomUUID;
        callable.call();
    }

}


================================================
FILE: src/com/winterbe/java8/samples/lambda/Lambda4.java
================================================
package com.winterbe.java8.samples.lambda;

/**
 * @author Benjamin Winterberg
 */
public class Lambda4 {

    static int outerStaticNum;

    int outerNum;

    void testScopes() {
        int num = 1;

        Lambda2.Converter<Integer, String> stringConverter =
                (from) -> String.valueOf(from + num);

        String convert = stringConverter.convert(2);
        System.out.println(convert);    // 3

        Lambda2.Converter<Integer, String> stringConverter2 = (from) -> {
            outerNum = 13;
            return String.valueOf(from);
        };

        String[] array = new String[1];
        Lambda2.Converter<Integer, String> stringConverter3 = (from) -> {
            array[0] = "Hi there";
            return String.valueOf(from);
        };

        stringConverter3.convert(23);

        System.out.println(array[0]);
    }

    public static void main(String[] args) {
        new Lambda4().testScopes();
    }

}

================================================
FILE: src/com/winterbe/java8/samples/lambda/Lambda5.java
================================================
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<String,Integer> 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<String, Integer> dummyValues = new HashMap<>();
        dummyValues.put("One", 1);
        dummyValues.put("Two", 2);
        dummyValues.put("Three", 3);

        dummyValues.forEach((key,value) -> System.out.println(key+"-"+value));

    }
}


================================================
FILE: src/com/winterbe/java8/samples/lambda/Person.java
================================================
package com.winterbe.java8.samples.lambda;

/**
* @author Benjamin Winterberg
*/
public class Person {
    public String firstName;
    public String lastName;

    public Person() {}

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

================================================
FILE: src/com/winterbe/java8/samples/misc/Annotations1.java
================================================
package com.winterbe.java8.samples.misc;

import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Benjamin Winterberg
 */
public class Annotations1 {

    @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE})
    @interface MyAnnotation {

    }

    @Retention(RetentionPolicy.RUNTIME)
    @interface Hints {
        Hint[] value();
    }

    @Repeatable(Hints.class)
    @Retention(RetentionPolicy.RUNTIME)
    @interface Hint {
        String value();
    }

    @Hint("hint1")
    @Hint("hint2")
    class Person {

    }

    public static void main(String[] args) {
        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

    }
}

================================================
FILE: src/com/winterbe/java8/samples/misc/CheckedFunctions.java
================================================
package com.winterbe.java8.samples.misc;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * Utilities for hassle-free usage of lambda expressions who throw checked exceptions.
 *
 * @author Benjamin Winterberg
 */
public final class CheckedFunctions {

    @FunctionalInterface
    public interface CheckedConsumer<T> {
        void accept(T input) throws Exception;
    }

    @FunctionalInterface
    public interface CheckedPredicate<T> {
        boolean test(T input) throws Exception;
    }

    @FunctionalInterface
    public interface CheckedFunction<F, T> {
        T apply(F input) throws Exception;
    }

    /**
     * Return a function which rethrows possible checked exceptions as runtime exception.
     *
     * @param function
     * @param <F>
     * @param <T>
     * @return
     */
    public static <F, T> Function<F, T> function(CheckedFunction<F, T> function) {
        return input -> {
            try {
                return function.apply(input);
            }
            catch (Exception e) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new RuntimeException(e);
            }
        };
    }

    /**
     * Return a predicate which rethrows possible checked exceptions as runtime exception.
     *
     * @param predicate
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> predicate(CheckedPredicate<T> predicate) {
        return input -> {
            try {
                return predicate.test(input);
            }
            catch (Exception e) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new RuntimeException(e);
            }
        };
    }

    /**
     * Return a consumer which rethrows possible checked exceptions as runtime exception.
     *
     * @param consumer
     * @param <T>
     * @return
     */
    public static <T> Consumer<T> consumer(CheckedConsumer<T> consumer) {
        return input -> {
            try {
                consumer.accept(input);
            }
            catch (Exception e) {
                if (e instanceof RuntimeException) {
                    throw (RuntimeException) e;
                }
                throw new RuntimeException(e);
            }
        };
    }
}


================================================
FILE: src/com/winterbe/java8/samples/misc/Concurrency1.java
================================================
package com.winterbe.java8.samples.misc;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Benjamin Winterberg
 */
public class Concurrency1 {

    public static void main(String[] args) {
        ConcurrentHashMap<Integer, UUID> concurrentHashMap = new ConcurrentHashMap<>();

        for (int i = 0; i < 100; i++) {
            concurrentHashMap.put(i, UUID.randomUUID());
        }

        int threshold = 1;

        concurrentHashMap.forEachValue(threshold, System.out::println);

        concurrentHashMap.forEach((id, uuid) -> {
            if (id % 10 == 0) {
                System.out.println(String.format("%s: %s", id, uuid));
            }
        });

        UUID searchResult = concurrentHashMap.search(threshold, (id, uuid) -> {
            if (String.valueOf(uuid).startsWith(String.valueOf(id))) {
                return uuid;
            }
            return null;
        });

        System.out.println(searchResult);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/misc/Files1.java
================================================
package com.winterbe.java8.samples.misc;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Benjamin Winterberg
 */
public class Files1 {

    public static void main(String[] args) throws IOException {
        testWalk();
        testFind();
        testList();
        testLines();
        testReader();
        testWriter();
        testReadWriteLines();
        testReaderLines();
    }

    private static void testReaderLines() throws IOException {
        Path path = Paths.get("res/nashorn1.js");
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            long countPrints = reader
                    .lines()
                    .filter(line -> line.contains("print"))
                    .count();
            System.out.println(countPrints);
        }
    }

    private static void testWriter() throws IOException {
        Path path = Paths.get("res/output.js");
        try (BufferedWriter writer = Files.newBufferedWriter(path)) {
            writer.write("print('Hello World');");
        }
    }

    private static void testReader() throws IOException {
        Path path = Paths.get("res/nashorn1.js");
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            System.out.println(reader.readLine());
        }
    }

    private static void testWalk() throws IOException {
        Path start = Paths.get("");
        int maxDepth = 5;
        try (Stream<Path> stream = Files.walk(start, maxDepth)) {
            String joined = stream
                    .map(String::valueOf)
                    .filter(path -> path.endsWith(".js"))
                    .collect(Collectors.joining("; "));
            System.out.println("walk(): " + joined);
        }
    }

    private static void testFind() throws IOException {
        Path start = Paths.get("");
        int maxDepth = 5;
        try (Stream<Path> stream = Files.find(start, maxDepth, (path, attr) ->
                String.valueOf(path).endsWith(".js"))) {
            String joined = stream
                    .sorted()
                    .map(String::valueOf)
                    .collect(Collectors.joining("; "));
            System.out.println("find(): " + joined);
        }
    }

    private static void testList() throws IOException {
        try (Stream<Path> stream = Files.list(Paths.get(""))) {
            String joined = stream
                    .map(String::valueOf)
                    .filter(path -> !path.startsWith("."))
                    .sorted()
                    .collect(Collectors.joining("; "));
            System.out.println("list(): " + joined);
        }
    }

    private static void testLines() throws IOException {
        try (Stream<String> stream = Files.lines(Paths.get("res/nashorn1.js"))) {
            stream
                    .filter(line -> line.contains("print"))
                    .map(String::trim)
                    .forEach(System.out::println);
        }
    }

    private static void testReadWriteLines() throws IOException {
        List<String> lines = Files.readAllLines(Paths.get("res/nashorn1.js"));
        lines.add("print('foobar');");
        Files.write(Paths.get("res", "nashorn1-modified.js"), lines);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/misc/Maps1.java
================================================
package com.winterbe.java8.samples.misc;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Benjamin Winterberg
 */
public class Maps1 {

    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();

        for (int i = 0; i < 10; i++) {
            map.putIfAbsent(i, "val" + i);
        }

        map.forEach((id, val) -> System.out.println(val));


        map.computeIfPresent(3, (num, val) -> val + num);
        System.out.println(map.get(3));             // val33

        map.computeIfPresent(9, (num, val) -> null);
        System.out.println(map.containsKey(9));     // false

        map.computeIfAbsent(23, num -> "val" + num);
        System.out.println(map.containsKey(23));    // true

        map.computeIfAbsent(3, num -> "bam");
        System.out.println(map.get(3));             // val33

        System.out.println(map.getOrDefault(42, "not found"));      // not found

        map.remove(3, "val3");
        System.out.println(map.get(3));             // val33

        map.remove(3, "val33");
        System.out.println(map.get(3));             // null

        map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
        System.out.println(map.get(9));             // val9

        map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
        System.out.println(map.get(9));             // val9concat
    }

}

================================================
FILE: src/com/winterbe/java8/samples/misc/Math1.java
================================================
package com.winterbe.java8.samples.misc;

/**
 * @author Benjamin Winterberg
 */
public class Math1 {

    public static void main(String[] args) {
        testMathExact();
        testUnsignedInt();
    }

    private static void testUnsignedInt() {
        try {
            Integer.parseUnsignedInt("-123", 10);
        }
        catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }

        long maxUnsignedInt = (1l << 32) - 1;
        System.out.println(maxUnsignedInt);

        String string = String.valueOf(maxUnsignedInt);

        int unsignedInt = Integer.parseUnsignedInt(string, 10);
        System.out.println(unsignedInt);

        String string2 = Integer.toUnsignedString(unsignedInt, 10);
        System.out.println(string2);

        try {
            Integer.parseInt(string, 10);
        }
        catch (NumberFormatException e) {
            System.err.println("could not parse signed int of " + maxUnsignedInt);
        }
    }

    private static void testMathExact() {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MAX_VALUE + 1);

        try {
            Math.addExact(Integer.MAX_VALUE, 1);
        }
        catch (ArithmeticException e) {
            System.err.println(e.getMessage());
        }

        try {
            Math.toIntExact(Long.MAX_VALUE);
        }
        catch (ArithmeticException e) {
            System.err.println(e.getMessage());
        }
    }
}


================================================
FILE: src/com/winterbe/java8/samples/misc/String1.java
================================================
package com.winterbe.java8.samples.misc;

import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Benjamin Winterberg
 */
public class String1 {

    public static void main(String[] args) {
        testJoin();
        testChars();
        testPatternPredicate();
        testPatternSplit();
    }

    private static void testChars() {
        String string = "foobar:foo:bar"
                .chars()
                .distinct()
                .mapToObj(c -> String.valueOf((char) c))
                .sorted()
                .collect(Collectors.joining());
        System.out.println(string);
    }

    private static void testPatternSplit() {
        String string = Pattern.compile(":")
                .splitAsStream("foobar:foo:bar")
                .filter(s -> s.contains("bar"))
                .sorted()
                .collect(Collectors.joining(":"));
        System.out.println(string);
    }

    private static void testPatternPredicate() {
        long count = Stream.of("bob@gmail.com", "alice@hotmail.com")
                .filter(Pattern.compile(".*@gmail\\.com").asPredicate())
                .count();
        System.out.println(count);
    }

    private static void testJoin() {
        String string = String.join(":", "foobar", "foo", "bar");
        System.out.println(string);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn1.java
================================================
package com.winterbe.java8.samples.nashorn;

import com.winterbe.java8.samples.lambda.Person;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * Calling javascript functions from java with nashorn.
 *
 * @author Benjamin Winterberg
 */
public class Nashorn1 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval(new FileReader("res/nashorn1.js"));

        Invocable invocable = (Invocable) engine;
        Object result = invocable.invokeFunction("fun1", "Peter Parker");
        System.out.println(result);
        System.out.println(result.getClass());

        invocable.invokeFunction("fun2", new Date());
        invocable.invokeFunction("fun2", LocalDateTime.now());
        invocable.invokeFunction("fun2", new Person());
    }

}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn10.java
================================================
package com.winterbe.java8.samples.nashorn;

import jdk.nashorn.api.scripting.NashornScriptEngine;

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Nashorn10 {

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn10.js')");

        long t0 = System.nanoTime();

        for (int i = 0; i < 100000; i++) {
            engine.invokeFunction("testPerf");
        }

        long took = System.nanoTime() - t0;
        System.out.format("Elapsed time: %d ms", TimeUnit.NANOSECONDS.toMillis(took));
    }
}


================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn11.java
================================================
package com.winterbe.java8.samples.nashorn;

import jdk.nashorn.api.scripting.NashornScriptEngine;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.SimpleBindings;
import javax.script.SimpleScriptContext;

/**
 * @author Benjamin Winterberg
 */
public class Nashorn11 {

    public static void main(String[] args) throws Exception {
//        test1();
//        test2();
//        test3();
//        test4();
//        test5();
//        test6();
//        test7();
        test8();
    }

    private static void test8() throws ScriptException {
        NashornScriptEngine engine = createEngine();

        engine.eval("var obj = { foo: 23 };");

        ScriptContext defaultContext = engine.getContext();
        Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context1 = new SimpleScriptContext();
        context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context2 = new SimpleScriptContext();
        context2.getBindings(ScriptContext.ENGINE_SCOPE).put("obj", defaultBindings.get("obj"));

        engine.eval("obj.foo = 44;", context1);
        engine.eval("print(obj.foo);", context1);
        engine.eval("print(obj.foo);", context2);
    }

    private static void test7() throws ScriptException {
        NashornScriptEngine engine = createEngine();

        engine.eval("var foo = 23;");

        ScriptContext defaultContext = engine.getContext();
        Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context1 = new SimpleScriptContext();
        context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context2 = new SimpleScriptContext();
        context2.getBindings(ScriptContext.ENGINE_SCOPE).put("foo", defaultBindings.get("foo"));

        engine.eval("foo = 44;", context1);
        engine.eval("print(foo);", context1);
        engine.eval("print(foo);", context2);
    }

    private static void test6() throws ScriptException {
        NashornScriptEngine engine = createEngine();

        ScriptContext defaultContext = engine.getContext();
        defaultContext.getBindings(ScriptContext.GLOBAL_SCOPE).put("foo", "hello");

        ScriptContext customContext = new SimpleScriptContext();
        customContext.setBindings(defaultContext.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.ENGINE_SCOPE);

        Bindings bindings = new SimpleBindings();
        bindings.put("foo", "world");
        customContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);

//        engine.eval("foo = 23;");                 // overrides foo in all contexts, why???

        engine.eval("print(foo)");                  // hello
        engine.eval("print(foo)", customContext);   // world
        engine.eval("print(foo)", defaultContext);  // hello
    }

    private static void test5() throws ScriptException {
        NashornScriptEngine engine = createEngine();

        engine.eval("var obj = { foo: 'foo' };");
        engine.eval("function printFoo() { print(obj.foo) };");

        ScriptContext defaultContext = engine.getContext();
        Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context1 = new SimpleScriptContext();
        context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context2 = new SimpleScriptContext();
        context2.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

        engine.eval("obj.foo = 'bar';", context1);
        engine.eval("printFoo();", context1);
        engine.eval("printFoo();", context2);
    }

    private static void test4() throws ScriptException {
        NashornScriptEngine engine = createEngine();

        engine.eval("function foo() { print('bar') };");

        ScriptContext defaultContext = engine.getContext();
        Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context = new SimpleScriptContext();
        context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

        engine.eval("foo();", context);
        System.out.println(context.getAttribute("foo"));
    }

    private static void test3() throws ScriptException {
        NashornScriptEngine engine = createEngine();

        ScriptContext defaultContext = engine.getContext();
        Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE);

        SimpleScriptContext context = new SimpleScriptContext();
        context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

        engine.eval("function foo() { print('bar') };", context);
        engine.eval("foo();", context);

        Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
        System.out.println(bindings.get("foo"));
        System.out.println(context.getAttribute("foo"));
    }

    private static void test2() throws ScriptException {
        NashornScriptEngine engine = createEngine();
        engine.eval("function foo() { print('bar') };");

        SimpleScriptContext context = new SimpleScriptContext();
        engine.eval("print(Function);", context);
        engine.eval("foo();", context);
    }

    private static void test1() throws ScriptException {
        NashornScriptEngine engine = createEngine();
        engine.eval("function foo() { print('bar') };");
        engine.eval("foo();");
    }

    private static NashornScriptEngine createEngine() {
        return (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
    }

}


================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn2.java
================================================
package com.winterbe.java8.samples.nashorn;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.util.Arrays;

/**
 * Calling java methods from javascript with nashorn.
 *
 * @author Benjamin Winterberg
 */
public class Nashorn2 {

    public static String fun(String name) {
        System.out.format("Hi there from Java, %s", name);
        return "greetings from java";
    }

    public static void fun2(Object object) {
        System.out.println(object.getClass());
    }

    public static void fun3(ScriptObjectMirror mirror) {
        System.out.println(mirror.getClassName() + ": " + Arrays.toString(mirror.getOwnKeys(true)));
    }

    public static void fun4(ScriptObjectMirror person) {
        System.out.println("Full Name is: " + person.callMember("getFullName"));
    }

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval(new FileReader("res/nashorn2.js"));
    }

}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn3.java
================================================
package com.winterbe.java8.samples.nashorn;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * Working with java types from javascript.
 *
 * @author Benjamin Winterberg
 */
public class Nashorn3 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn3.js')");
    }

}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn4.java
================================================
package com.winterbe.java8.samples.nashorn;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * Working with java types from javascript.
 *
 * @author Benjamin Winterberg
 */
public class Nashorn4 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("loadWithNewGlobal('res/nashorn4.js')");
    }

}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn5.java
================================================
package com.winterbe.java8.samples.nashorn;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * Bind java objects to custom javascript objects.
 *
 * @author Benjamin Winterberg
 */
public class Nashorn5 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn5.js')");

        Invocable invocable = (Invocable) engine;

        Product product = new Product();
        product.setName("Rubber");
        product.setPrice(1.99);
        product.setStock(1037);

        Object result = invocable.invokeFunction("getValueOfGoods", product);
        System.out.println(result);
    }

}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn6.java
================================================
package com.winterbe.java8.samples.nashorn;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

/**
 * Using Backbone Models from Nashorn.
 *
 * @author Benjamin Winterberg
 */
public class Nashorn6 {

    public static void main(String[] args) throws Exception {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn6.js')");

        Invocable invocable = (Invocable) engine;

        Product product = new Product();
        product.setName("Rubber");
        product.setPrice(1.99);
        product.setStock(1337);

        ScriptObjectMirror result = (ScriptObjectMirror)
                invocable.invokeFunction("calculate", product);
        System.out.println(result.get("name") + ": " + result.get("valueOfGoods"));
    }

    public static void getProduct(ScriptObjectMirror result) {
        System.out.println(result.get("name") + ": " + result.get("valueOfGoods"));
    }

}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn7.java
================================================
package com.winterbe.java8.samples.nashorn;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author Benjamin Winterberg
 */
public class Nashorn7 {

    public static class Person {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getLengthOfName() {
            return name.length();
        }
    }

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("function foo(predicate, obj) { return !!(eval(predicate)); };");

        Invocable invocable = (Invocable) engine;

        Person person = new Person();
        person.setName("Hans");

        String predicate = "obj.getLengthOfName() >= 4";
        Object result = invocable.invokeFunction("foo", predicate, person);
        System.out.println(result);
    }

}


================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn8.java
================================================
package com.winterbe.java8.samples.nashorn;

import com.winterbe.java8.samples.lambda.Person;
import jdk.nashorn.api.scripting.NashornScriptEngine;

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

/**
 * @author Benjamin Winterberg
 */
public class Nashorn8 {
    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn8.js')");

        engine.invokeFunction("evaluate1");                             // [object global]
        engine.invokeFunction("evaluate2");                             // [object Object]
        engine.invokeFunction("evaluate3", "Foobar");                   // Foobar
        engine.invokeFunction("evaluate3", new Person("John", "Doe"));  // [object global] <- ???????
    }

}


================================================
FILE: src/com/winterbe/java8/samples/nashorn/Nashorn9.java
================================================
package com.winterbe.java8.samples.nashorn;

import jdk.nashorn.api.scripting.NashornScriptEngine;

import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Nashorn9 {

    public static void main(String[] args) throws ScriptException, NoSuchMethodException {
        NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
        engine.eval("load('res/nashorn9.js')");

        long t0 = System.nanoTime();

        double result = 0;
        for (int i = 0; i < 1000; i++) {
            double num = (double) engine.invokeFunction("testPerf");
            result += num;
        }

        System.out.println(result > 0);

        long took = System.nanoTime() - t0;
        System.out.format("Elapsed time: %d ms", TimeUnit.NANOSECONDS.toMillis(took));
    }
}


================================================
FILE: src/com/winterbe/java8/samples/nashorn/Product.java
================================================
package com.winterbe.java8.samples.nashorn;

/**
 * @author Benjamin Winterberg
 */
public class Product {
    private String name;
    private double price;
    private int stock;
    private double valueOfGoods;

    public double getValueOfGoods() {
        return valueOfGoods;
    }

    public void setValueOfGoods(double valueOfGoods) {
        this.valueOfGoods = valueOfGoods;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }
}

================================================
FILE: src/com/winterbe/java8/samples/nashorn/SuperRunner.java
================================================
package com.winterbe.java8.samples.nashorn;

/**
 * @author Benjamin Winterberg
 */
public class SuperRunner implements Runnable {

    @Override
    public void run() {
        System.out.println("super run");
    }

}

================================================
FILE: src/com/winterbe/java8/samples/stream/Optional1.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Optional;

/**
 * @author Benjamin Winterberg
 */
public class Optional1 {

    public static void main(String[] args) {
        Optional<String> optional = Optional.of("bam");

        optional.isPresent();           // true
        optional.get();                 // "bam"
        optional.orElse("fallback");    // "bam"

        optional.ifPresent((s) -> System.out.println(s.charAt(0)));     // "b"
    }

}

================================================
FILE: src/com/winterbe/java8/samples/stream/Optional2.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Optional;
import java.util.function.Supplier;

/**
 * Examples how to avoid null checks with Optional:
 *
 * http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/
 *
 * @author Benjamin Winterberg
 */
public class Optional2 {

    static class Outer {
        Nested nested = new Nested();

        public Nested getNested() {
            return nested;
        }
    }

    static class Nested {
        Inner inner = new Inner();

        public Inner getInner() {
            return inner;
        }
    }

    static class Inner {
        String foo = "boo";

        public String getFoo() {
            return foo;
        }
    }

    public static void main(String[] args) {
        test1();
        test2();
        test3();
    }

    public static <T> Optional<T> resolve(Supplier<T> resolver) {
        try {
            T result = resolver.get();
            return Optional.ofNullable(result);
        }
        catch (NullPointerException e) {
            return Optional.empty();
        }
    }

    private static void test3() {
        Outer outer = new Outer();
        resolve(() -> outer.getNested().getInner().getFoo())
                .ifPresent(System.out::println);
    }

    private static void test2() {
        Optional.of(new Outer())
                .map(Outer::getNested)
                .map(Nested::getInner)
                .map(Inner::getFoo)
                .ifPresent(System.out::println);
    }

    private static void test1() {
        Optional.of(new Outer())
                .flatMap(o -> Optional.ofNullable(o.nested))
                .flatMap(n -> Optional.ofNullable(n.inner))
                .flatMap(i -> Optional.ofNullable(i.foo))
                .ifPresent(System.out::println);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams1.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author Benjamin Winterberg
 */
public class Streams1 {

    public static void main(String[] args) {

        List<String> 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");


        // filtering

        stringCollection
                .stream()
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);

        // "aaa2", "aaa1"


        // sorting

        stringCollection
                .stream()
                .sorted()
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);

        // "aaa1", "aaa2"


        // mapping

        stringCollection
                .stream()
                .map(String::toUpperCase)
                .sorted((a, b) -> b.compareTo(a))
                .forEach(System.out::println);

        // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"


        // matching

        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


        // counting

        long startsWithB = stringCollection
                .stream()
                .filter((s) -> s.startsWith("b"))
                .count();

        System.out.println(startsWithB);    // 3


        // reducing

        Optional<String> reduced =
                stringCollection
                        .stream()
                        .sorted()
                        .reduce((s1, s2) -> s1 + "#" + s2);

        reduced.ifPresent(System.out::println);
        // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"


    }

}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams10.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author Benjamin Winterberg
 */
public class Streams10 {

    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Person> persons =
            Arrays.asList(
                new Person("Max", 18),
                new Person("Peter", 23),
                new Person("Pamela", 23),
                new Person("David", 12));

//        test1(persons);
//        test2(persons);
//        test3(persons);
//        test4(persons);
//        test5(persons);
//        test6(persons);
//        test7(persons);
//        test8(persons);
        test9(persons);
    }

    private static void test1(List<Person> persons) {
        List<Person> filtered =
            persons
                .stream()
                .filter(p -> p.name.startsWith("P"))
                .collect(Collectors.toList());

        System.out.println(filtered);    // [Peter, Pamela]
    }

    private static void test2(List<Person> persons) {
        Map<Integer, List<Person>> personsByAge = persons
            .stream()
            .collect(Collectors.groupingBy(p -> p.age));

        personsByAge
            .forEach((age, p) -> System.out.format("age %s: %s\n", age, p));

        // age 18: [Max]
        // age 23:[Peter, Pamela]
        // age 12:[David]
    }

    private static void test3(List<Person> persons) {
        Double averageAge = persons
            .stream()
            .collect(Collectors.averagingInt(p -> p.age));

        System.out.println(averageAge);     // 19.0
    }

    private static void test4(List<Person> persons) {
        IntSummaryStatistics ageSummary =
            persons
                .stream()
                .collect(Collectors.summarizingInt(p -> p.age));

        System.out.println(ageSummary);
        // IntSummaryStatistics{count=4, sum=76, min=12, average=19,000000, max=23}
    }

    private static void test5(List<Person> persons) {
        String names = persons
            .stream()
            .filter(p -> p.age >= 18)
            .map(p -> p.name)
            .collect(Collectors.joining(" and ", "In Germany ", " are of legal age."));

        System.out.println(names);
        // In Germany Max and Peter and Pamela are of legal age.
    }

    private static void test6(List<Person> persons) {
        Map<Integer, String> map = persons
            .stream()
            .collect(Collectors.toMap(
                p -> p.age,
                p -> p.name,
                (name1, name2) -> name1 + ";" + name2));

        System.out.println(map);
        // {18=Max, 23=Peter;Pamela, 12=David}
    }

    private static void test7(List<Person> persons) {
        Collector<Person, StringJoiner, String> personNameCollector =
            Collector.of(
                () -> new StringJoiner(" | "),          // supplier
                (j, p) -> j.add(p.name.toUpperCase()),  // accumulator
                (j1, j2) -> j1.merge(j2),               // combiner
                StringJoiner::toString);                // finisher

        String names = persons
            .stream()
            .collect(personNameCollector);

        System.out.println(names);  // MAX | PETER | PAMELA | DAVID
    }

    private static void test8(List<Person> persons) {
        Collector<Person, StringJoiner, String> personNameCollector =
            Collector.of(
                () -> {
                    System.out.println("supplier");
                    return new StringJoiner(" | ");
                },
                (j, p) -> {
                    System.out.format("accumulator: p=%s; j=%s\n", p, j);
                    j.add(p.name.toUpperCase());
                },
                (j1, j2) -> {
                    System.out.println("merge");
                    return j1.merge(j2);
                },
                j -> {
                    System.out.println("finisher");
                    return j.toString();
                });

        String names = persons
            .stream()
            .collect(personNameCollector);

        System.out.println(names);  // MAX | PETER | PAMELA | DAVID
    }

    private static void test9(List<Person> persons) {
        Collector<Person, StringJoiner, String> personNameCollector =
            Collector.of(
                () -> {
                    System.out.println("supplier");
                    return new StringJoiner(" | ");
                },
                (j, p) -> {
                    System.out.format("accumulator: p=%s; j=%s\n", p, j);
                    j.add(p.name.toUpperCase());
                },
                (j1, j2) -> {
                    System.out.println("merge");
                    return j1.merge(j2);
                },
                j -> {
                    System.out.println("finisher");
                    return j.toString();
                });

        String names = persons
            .parallelStream()
            .collect(personNameCollector);

        System.out.println(names);  // MAX | PETER | PAMELA | DAVID
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams11.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Arrays;
import java.util.List;

/**
 * @author Benjamin Winterberg
 */
public class Streams11 {

    static class Person {
        String name;
        int age;

        Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Person> persons =
            Arrays.asList(
                new Person("Max", 18),
                new Person("Peter", 23),
                new Person("Pamela", 23),
                new Person("David", 12));

//        test1(persons);
//        test2(persons);
//        test3(persons);
//        test4(persons);
//        test5(persons);
        test6(persons);
    }

    private static void test1(List<Person> persons) {
        persons
            .stream()
            .reduce((p1, p2) -> p1.age > p2.age ? p1 : p2)
            .ifPresent(System.out::println);    // Pamela
    }

    private static void test2(List<Person> persons) {
        Person result =
            persons
                .stream()
                .reduce(new Person("", 0), (p1, p2) -> {
                    p1.age += p2.age;
                    p1.name += p2.name;
                    return p1;
                });

        System.out.format("name=%s; age=%s", result.name, result.age);
    }

    private static void test3(List<Person> persons) {
        Integer ageSum = persons
            .stream()
            .reduce(0, (sum, p) -> sum += p.age, (sum1, sum2) -> sum1 + sum2);

        System.out.println(ageSum);
    }

    private static void test4(List<Person> persons) {
        Integer ageSum = persons
            .stream()
            .reduce(0,
                (sum, p) -> {
                    System.out.format("accumulator: sum=%s; person=%s\n", sum, p);
                    return sum += p.age;
                },
                (sum1, sum2) -> {
                    System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2);
                    return sum1 + sum2;
                });

        System.out.println(ageSum);
    }

    private static void test5(List<Person> persons) {
        Integer ageSum = persons
            .parallelStream()
            .reduce(0,
                (sum, p) -> {
                    System.out.format("accumulator: sum=%s; person=%s\n", sum, p);
                    return sum += p.age;
                },
                (sum1, sum2) -> {
                    System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2);
                    return sum1 + sum2;
                });

        System.out.println(ageSum);
    }

    private static void test6(List<Person> persons) {
        Integer ageSum = persons
            .parallelStream()
            .reduce(0,
                (sum, p) -> {
                    System.out.format("accumulator: sum=%s; person=%s; thread=%s\n",
                        sum, p, Thread.currentThread().getName());
                    return sum += p.age;
                },
                (sum1, sum2) -> {
                    System.out.format("combiner: sum1=%s; sum2=%s; thread=%s\n",
                        sum1, sum2, Thread.currentThread().getName());
                    return sum1 + sum2;
                });

        System.out.println(ageSum);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams12.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Streams12 {

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("a1", "a2", "b1", "c2", "c1");

//        test1();
//        test2(strings);
        test3(strings);
//        test4();
    }

    private static void test4() {
        List<String> values = new ArrayList<>(100);
        for (int i = 0; i < 100; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }

        // sequential

        long t0 = System.nanoTime();

        long count = values
            .parallelStream()
            .sorted((s1, s2) -> {
                System.out.format("sort:    %s <> %s [%s]\n", s1, s2, Thread.currentThread().getName());
                return s1.compareTo(s2);
            })
            .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));
    }

    private static void test3(List<String> strings) {
        strings
            .parallelStream()
            .filter(s -> {
                System.out.format("filter:  %s [%s]\n", s, Thread.currentThread().getName());
                return true;
            })
            .map(s -> {
                System.out.format("map:     %s [%s]\n", s, Thread.currentThread().getName());
                return s.toUpperCase();
            })
            .sorted((s1, s2) -> {
                System.out.format("sort:    %s <> %s [%s]\n", s1, s2, Thread.currentThread().getName());
                return s1.compareTo(s2);
            })
            .forEach(s -> System.out.format("forEach: %s [%s]\n", s, Thread.currentThread().getName()));
    }

    private static void test2(List<String> strings) {
        strings
            .parallelStream()
            .filter(s -> {
                System.out.format("filter:  %s [%s]\n", s, Thread.currentThread().getName());
                return true;
            })
            .map(s -> {
                System.out.format("map:     %s [%s]\n", s, Thread.currentThread().getName());
                return s.toUpperCase();
            })
            .forEach(s -> System.out.format("forEach: %s [%s]\n", s, Thread.currentThread().getName()));
    }

    private static void test1() {
        // -Djava.util.concurrent.ForkJoinPool.common.parallelism=5

        ForkJoinPool commonPool = ForkJoinPool.commonPool();
        System.out.println(commonPool.getParallelism());
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams13.java
================================================
package com.winterbe.java8.samples.stream;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Streams13 {

    public static void main(String[] args) {
        SecureRandom secureRandom = new SecureRandom(new byte[]{1, 3, 3, 7});
        int[] randoms = IntStream.generate(secureRandom::nextInt)
                .filter(n -> n > 0)
                .limit(10)
                .toArray();
        System.out.println(Arrays.toString(randoms));


        int[] nums = IntStream.iterate(1, n -> n * 2)
                .limit(11)
                .toArray();
        System.out.println(Arrays.toString(nums));
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams2.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Benjamin Winterberg
 */
public class Streams2 {

    public static void main(String[] args) {

        List<String> 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");


        // sorting

        stringCollection
                .stream()
                .sorted()
                .forEach(System.out::println);

        System.out.println(stringCollection);

        

    }

}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams3.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Benjamin Winterberg
 */
public class Streams3 {

    public static final int MAX = 1000000;

    public static void sortSequential() {
        List<String> values = new ArrayList<>(MAX);
        for (int i = 0; i < MAX; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }

        // sequential

        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));
    }

    public static void sortParallel() {
        List<String> values = new ArrayList<>(MAX);
        for (int i = 0; i < MAX; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }

        // sequential

        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));
    }

    public static void main(String[] args) {
        sortSequential();
        sortParallel();
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams4.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.OptionalInt;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Streams4 {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 1) {
                System.out.println(i);
            }
        }

        IntStream.range(0, 10)
            .forEach(i -> {
                if (i % 2 == 1) System.out.println(i);
            });

        IntStream.range(0, 10)
            .filter(i -> i % 2 == 1)
            .forEach(System.out::println);

        OptionalInt reduced1 =
            IntStream.range(0, 10)
                .reduce((a, b) -> a + b);
        System.out.println(reduced1.getAsInt());

        int reduced2 =
            IntStream.range(0, 10)
                .reduce(7, (a, b) -> a + b);
        System.out.println(reduced2);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams5.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
 * Testing the order of execution.
 *
 * @author Benjamin Winterberg
 */
public class Streams5 {

    public static void main(String[] args) {
        List<String> strings =
            Arrays.asList("d2", "a2", "b1", "b3", "c");

//        test1(strings);
//        test2(strings);
//        test3(strings);
//        test4(strings);
//        test5(strings);
//        test6(strings);
//        test7(strings);
        test8(strings);
    }

    private static void test8(List<String> stringCollection) {
        Supplier<Stream<String>> streamSupplier =
            () -> stringCollection
                .stream()
                .filter(s -> s.startsWith("a"));

        streamSupplier.get().anyMatch(s -> true);
        streamSupplier.get().noneMatch(s -> true);
    }

    // stream has already been operated upon or closed
    private static void test7(List<String> stringCollection) {
        Stream<String> stream = stringCollection
            .stream()
            .filter(s -> s.startsWith("a"));

        stream.anyMatch(s -> true);
        stream.noneMatch(s -> true);
    }

    // short-circuit
    private static void test6(List<String> stringCollection) {
        stringCollection
            .stream()
            .map(s -> {
                System.out.println("map:      " + s);
                return s.toUpperCase();
            })
            .anyMatch(s -> {
                System.out.println("anyMatch: " + s);
                return s.startsWith("A");
            });
    }

    private static void test5(List<String> stringCollection) {
        stringCollection
            .stream()
            .filter(s -> {
                System.out.println("filter:  " + s);
                return s.toLowerCase().startsWith("a");
            })
            .sorted((s1, s2) -> {
                System.out.printf("sort:    %s; %s\n", s1, s2);
                return s1.compareTo(s2);
            })
            .map(s -> {
                System.out.println("map:     " + s);
                return s.toUpperCase();
            })
            .forEach(s -> System.out.println("forEach: " + s));
    }

    // sorted = horizontal
    private static void test4(List<String> stringCollection) {
        stringCollection
            .stream()
            .sorted((s1, s2) -> {
                System.out.printf("sort:    %s; %s\n", s1, s2);
                return s1.compareTo(s2);
            })
            .filter(s -> {
                System.out.println("filter:  " + s);
                return s.toLowerCase().startsWith("a");
            })
            .map(s -> {
                System.out.println("map:     " + s);
                return s.toUpperCase();
            })
            .forEach(s -> System.out.println("forEach: " + s));
    }

    private static void test3(List<String> stringCollection) {
        stringCollection
            .stream()
            .filter(s -> {
                System.out.println("filter:  " + s);
                return s.startsWith("a");
            })
            .map(s -> {
                System.out.println("map:     " + s);
                return s.toUpperCase();
            })
            .forEach(s -> System.out.println("forEach: " + s));
    }

    private static void test2(List<String> stringCollection) {
        stringCollection
            .stream()
            .map(s -> {
                System.out.println("map:     " + s);
                return s.toUpperCase();
            })
            .filter(s -> {
                System.out.println("filter:  " + s);
                return s.startsWith("A");
            })
            .forEach(s -> System.out.println("forEach: " + s));
    }

    private static void test1(List<String> stringCollection) {
        stringCollection
            .stream()
            .filter(s -> {
                System.out.println("filter:  " + s);
                return true;
            })
            .forEach(s -> System.out.println("forEach: " + s));
    }

}

================================================
FILE: src/com/winterbe/java8/samples/stream/Streams6.java
================================================
package com.winterbe.java8.samples.stream;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author Benjamin Winterberg
 */
public class Streams6 {

    public static void main(String[] args) throws IOException {
        test1();
        test2();
        test3();
        test4();
    }

    private static void test4() {
        Stream
            .of(new BigDecimal("1.2"), new BigDecimal("3.7"))
            .mapToDouble(BigDecimal::doubleValue)
            .average()
            .ifPresent(System.out::println);
    }

    private static void test3() {
        IntStream
            .range(0, 10)
            .average()
            .ifPresent(System.out::println);
    }

    private static void test2() {
        IntStream
            .builder()
            .add(1)
            .add(3)
            .add(5)
            .add(7)
            .add(11)
            .build()
            .average()
            .ifPresent(System.out::println);

    }

    private static void test1() {
        int[] ints = {1, 3, 5, 7, 11};
        Arrays
            .stream(ints)
            .average()
            .ifPresent(System.out::println);
    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams7.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

/**
 * @author Benjamin Winterberg
 */
public class Streams7 {

    static class Foo {
        String name;
        List<Bar> bars = new ArrayList<>();

        Foo(String name) {
            this.name = name;
        }
    }

    static class Bar {
        String name;

        Bar(String name) {
            this.name = name;
        }
    }

    public static void main(String[] args) {
//        test1();
        test2();
    }

    static void test2() {
        IntStream.range(1, 4)
            .mapToObj(num -> new Foo("Foo" + num))
            .peek(f -> IntStream.range(1, 4)
                .mapToObj(num -> new Bar("Bar" + num + " <- " + f.name))
                .forEach(f.bars::add))
            .flatMap(f -> f.bars.stream())
            .forEach(b -> System.out.println(b.name));
    }

    static void test1() {
        List<Foo> foos = new ArrayList<>();

        IntStream
            .range(1, 4)
            .forEach(num -> foos.add(new Foo("Foo" + num)));

        foos.forEach(f ->
            IntStream
                .range(1, 4)
                .forEach(num -> f.bars.add(new Bar("Bar" + num + " <- " + f.name))));

        foos.stream()
            .flatMap(f -> f.bars.stream())
            .forEach(b -> System.out.println(b.name));
    }

}

================================================
FILE: src/com/winterbe/java8/samples/stream/Streams8.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * @author Benjamin Winterberg
 */
public class Streams8 {

    public static void main(String[] args) {
        Arrays.asList("a1", "a2", "a3")
            .stream()
            .findFirst()
            .ifPresent(System.out::println);

        Stream.of("a1", "a2", "a3")
            .map(s -> s.substring(1))
            .mapToInt(Integer::parseInt)
            .max()
            .ifPresent(System.out::println);

        IntStream.range(1, 4)
            .mapToObj(i -> "a" + i)
            .forEach(System.out::println);

        Arrays.stream(new int[] {1, 2, 3})
            .map(n -> 2 * n + 1)
            .average()
            .ifPresent(System.out::println);

        Stream.of(1.0, 2.0, 3.0)
            .mapToInt(Double::intValue)
            .mapToObj(i -> "a" + i)
            .forEach(System.out::println);

    }
}


================================================
FILE: src/com/winterbe/java8/samples/stream/Streams9.java
================================================
package com.winterbe.java8.samples.stream;

import java.util.Arrays;

/**
 * @author Benjamin Winterberg
 */
public class Streams9 {

    public static void main(String[] args) {
        Arrays.asList("a1", "a2", "b1", "c2", "c1")
            .stream()
            .filter(s -> s.startsWith("c"))
            .map(String::toUpperCase)
            .sorted()
            .forEach(System.out::println);

        // C1
        // C2
    }
}


================================================
FILE: src/com/winterbe/java8/samples/time/LocalDate1.java
================================================
package com.winterbe.java8.samples.time;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.Locale;

/**
 * @author Benjamin Winterberg
 */
public class LocalDate1 {

    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
        LocalDate yesterday = tomorrow.minusDays(2);

        System.out.println(today);
        System.out.println(tomorrow);
        System.out.println(yesterday);

        LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
        DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
        System.out.println(dayOfWeek);    // FRIDAY

        DateTimeFormatter germanFormatter =
                DateTimeFormatter
                        .ofLocalizedDate(FormatStyle.MEDIUM)
                        .withLocale(Locale.GERMAN);

        LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter);
        System.out.println(xmas);   // 2014-12-24


    }

}

================================================
FILE: src/com/winterbe/java8/samples/time/LocalDateTime1.java
================================================
package com.winterbe.java8.samples.time;

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.Date;

/**
 * @author Benjamin Winterberg
 */
public class LocalDateTime1 {

    public static void main(String[] args) {

        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

        Instant instant = sylvester
                .atZone(ZoneId.systemDefault())
                .toInstant();

        Date legacyDate = Date.from(instant);
        System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014


        DateTimeFormatter formatter =
                DateTimeFormatter
                        .ofPattern("MMM dd, yyyy - HH:mm");

        LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
        String string = parsed.format(formatter);
        System.out.println(string);     // Nov 03, 2014 - 07:13
    }

}

================================================
FILE: src/com/winterbe/java8/samples/time/LocalTime1.java
================================================
package com.winterbe.java8.samples.time;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Locale;

/**
 * @author Benjamin Winterberg
 */
public class LocalTime1 {

    public static void main(String[] args) {

        // get the current time
        Clock clock = Clock.systemDefaultZone();
        long t0 = clock.millis();
        System.out.println(t0);

        Instant instant = clock.instant();
        Date legacyDate = Date.from(instant);


        ZoneId zone1 = ZoneId.of("Europe/Berlin");
        ZoneId zone2 = ZoneId.of("Brazil/East");

        System.out.println(zone1.getRules());
        System.out.println(zone2.getRules());

        // time
        LocalTime now1 = LocalTime.now(zone1);
        LocalTime now2 = LocalTime.now(zone2);

        System.out.println(now1);
        System.out.println(now2);

        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);
        System.out.println(minutesBetween);


        // create time

        LocalTime now = LocalTime.now();
        System.out.println(now);

        LocalTime late = LocalTime.of(23, 59, 59);
        System.out.println(late);

        DateTimeFormatter germanFormatter =
                DateTimeFormatter
                        .ofLocalizedTime(FormatStyle.SHORT)
                        .withLocale(Locale.GERMAN);

        LocalTime leetTime = LocalTime.parse("13:37", germanFormatter);
        System.out.println(leetTime);


        // to legacy date


    }

}
Download .txt
gitextract_v1c0ly93/

├── .gitignore
├── LICENSE
├── README.md
├── res/
│   ├── nashorn1.js
│   ├── nashorn10.js
│   ├── nashorn2.js
│   ├── nashorn3.js
│   ├── nashorn4.js
│   ├── nashorn5.js
│   ├── nashorn6.js
│   ├── nashorn7.js
│   ├── nashorn8.js
│   └── nashorn9.js
└── src/
    └── com/
        └── winterbe/
            ├── java11/
            │   ├── HttpClientExamples.java
            │   ├── LocalVariableSyntax.java
            │   ├── Misc.java
            │   └── dummy.txt
            └── java8/
                └── samples/
                    ├── concurrent/
                    │   ├── Atomic1.java
                    │   ├── CompletableFuture1.java
                    │   ├── ConcurrentHashMap1.java
                    │   ├── ConcurrentUtils.java
                    │   ├── Executors1.java
                    │   ├── Executors2.java
                    │   ├── Executors3.java
                    │   ├── Lock1.java
                    │   ├── Lock2.java
                    │   ├── Lock3.java
                    │   ├── Lock4.java
                    │   ├── Lock5.java
                    │   ├── Lock6.java
                    │   ├── LongAccumulator1.java
                    │   ├── LongAdder1.java
                    │   ├── Semaphore1.java
                    │   ├── Semaphore2.java
                    │   ├── Synchronized1.java
                    │   ├── Synchronized2.java
                    │   └── Threads1.java
                    ├── lambda/
                    │   ├── Interface1.java
                    │   ├── Lambda1.java
                    │   ├── Lambda2.java
                    │   ├── Lambda3.java
                    │   ├── Lambda4.java
                    │   ├── Lambda5.java
                    │   └── Person.java
                    ├── misc/
                    │   ├── Annotations1.java
                    │   ├── CheckedFunctions.java
                    │   ├── Concurrency1.java
                    │   ├── Files1.java
                    │   ├── Maps1.java
                    │   ├── Math1.java
                    │   └── String1.java
                    ├── nashorn/
                    │   ├── Nashorn1.java
                    │   ├── Nashorn10.java
                    │   ├── Nashorn11.java
                    │   ├── Nashorn2.java
                    │   ├── Nashorn3.java
                    │   ├── Nashorn4.java
                    │   ├── Nashorn5.java
                    │   ├── Nashorn6.java
                    │   ├── Nashorn7.java
                    │   ├── Nashorn8.java
                    │   ├── Nashorn9.java
                    │   ├── Product.java
                    │   └── SuperRunner.java
                    ├── stream/
                    │   ├── Optional1.java
                    │   ├── Optional2.java
                    │   ├── Streams1.java
                    │   ├── Streams10.java
                    │   ├── Streams11.java
                    │   ├── Streams12.java
                    │   ├── Streams13.java
                    │   ├── Streams2.java
                    │   ├── Streams3.java
                    │   ├── Streams4.java
                    │   ├── Streams5.java
                    │   ├── Streams6.java
                    │   ├── Streams7.java
                    │   ├── Streams8.java
                    │   └── Streams9.java
                    └── time/
                        ├── LocalDate1.java
                        ├── LocalDateTime1.java
                        └── LocalTime1.java
Download .txt
SYMBOL INDEX (300 symbols across 70 files)

FILE: res/nashorn2.js
  function Person (line 25) | function Person(firstName, lastName) {

FILE: res/nashorn5.js
  function Product (line 1) | function Product(name) {

FILE: src/com/winterbe/java11/HttpClientExamples.java
  class HttpClientExamples (line 12) | public class HttpClientExamples {
    method main (line 14) | public static void main(String[] args) throws IOException, Interrupted...
    method syncRequest (line 21) | private static void syncRequest() throws IOException, InterruptedExcep...
    method asyncRequest (line 30) | private static void asyncRequest() {
    method postData (line 40) | private static void postData() throws IOException, InterruptedException {
    method basicAuth (line 53) | private static void basicAuth() throws IOException, InterruptedExcepti...

FILE: src/com/winterbe/java11/LocalVariableSyntax.java
  class LocalVariableSyntax (line 8) | public class LocalVariableSyntax {
    method main (line 10) | public static void main(String[] args) {
    method someMethod (line 35) | void someMethod() {}

FILE: src/com/winterbe/java11/Misc.java
  class Misc (line 12) | public class Misc {
    method main (line 17) | public static void main(String[] args) throws IOException {
    method streams (line 25) | private static void streams() {
    method inputStreams (line 35) | private static void inputStreams() throws IOException {
    method optionals (line 45) | private static void optionals() {
    method strings (line 51) | private static void strings() {
    method collections (line 60) | private static void collections() {

FILE: src/com/winterbe/java8/samples/concurrent/Atomic1.java
  class Atomic1 (line 11) | public class Atomic1 {
    method main (line 17) | public static void main(String[] args) {
    method testUpdate (line 23) | private static void testUpdate() {
    method testAccumulate (line 40) | private static void testAccumulate() {
    method testIncrement (line 57) | private static void testIncrement() {

FILE: src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java
  class CompletableFuture1 (line 9) | public class CompletableFuture1 {
    method main (line 11) | public static void main(String[] args) throws ExecutionException, Inte...

FILE: src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java
  class ConcurrentHashMap1 (line 9) | public class ConcurrentHashMap1 {
    method main (line 11) | public static void main(String[] args) {
    method testReduce (line 19) | private static void testReduce() {
    method testSearch (line 32) | private static void testSearch() {
    method testForEach (line 64) | private static void testForEach() {

FILE: src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java
  class ConcurrentUtils (line 9) | public class ConcurrentUtils {
    method stop (line 11) | public static void stop(ExecutorService executor) {
    method sleep (line 27) | public static void sleep(int seconds) {

FILE: src/com/winterbe/java8/samples/concurrent/Executors1.java
  class Executors1 (line 10) | public class Executors1 {
    method main (line 12) | public static void main(String[] args) {
    method test1 (line 17) | private static void test1(long seconds) {
    method stop (line 32) | static void stop(ExecutorService executor) {

FILE: src/com/winterbe/java8/samples/concurrent/Executors2.java
  class Executors2 (line 13) | public class Executors2 {
    method main (line 15) | public static void main(String[] args) throws ExecutionException, Inte...
    method test3 (line 21) | private static void test3() throws InterruptedException, ExecutionExce...
    method test2 (line 37) | private static void test2() throws InterruptedException, ExecutionExce...
    method test1 (line 54) | private static void test1() throws InterruptedException, ExecutionExce...

FILE: src/com/winterbe/java8/samples/concurrent/Executors3.java
  class Executors3 (line 16) | public class Executors3 {
    method main (line 18) | public static void main(String[] args) throws InterruptedException, Ex...
    method test5 (line 27) | private static void test5() throws InterruptedException, ExecutionExce...
    method callable (line 41) | private static Callable<String> callable(String result, long sleepSeco...
    method test4 (line 48) | private static void test4() throws InterruptedException {
    method test3 (line 71) | private static void test3() {
    method test2 (line 87) | private static void test2() {
    method test1 (line 95) | private static void test1() throws InterruptedException {

FILE: src/com/winterbe/java8/samples/concurrent/Lock1.java
  class Lock1 (line 11) | public class Lock1 {
    method increment (line 19) | private static void increment() {
    method main (line 28) | public static void main(String[] args) {
    method testLock (line 32) | private static void testLock() {

FILE: src/com/winterbe/java8/samples/concurrent/Lock2.java
  class Lock2 (line 10) | public class Lock2 {
    method main (line 12) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/concurrent/Lock3.java
  class Lock3 (line 13) | public class Lock3 {
    method main (line 15) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/concurrent/Lock4.java
  class Lock4 (line 12) | public class Lock4 {
    method main (line 14) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/concurrent/Lock5.java
  class Lock5 (line 10) | public class Lock5 {
    method main (line 12) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/concurrent/Lock6.java
  class Lock6 (line 10) | public class Lock6 {
    method main (line 14) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java
  class LongAccumulator1 (line 12) | public class LongAccumulator1 {
    method main (line 14) | public static void main(String[] args) {
    method testAccumulate (line 18) | private static void testAccumulate() {

FILE: src/com/winterbe/java8/samples/concurrent/LongAdder1.java
  class LongAdder1 (line 11) | public class LongAdder1 {
    method main (line 17) | public static void main(String[] args) {
    method testAdd (line 22) | private static void testAdd() {
    method testIncrement (line 33) | private static void testIncrement() {

FILE: src/com/winterbe/java8/samples/concurrent/Semaphore1.java
  class Semaphore1 (line 12) | public class Semaphore1 {
    method main (line 20) | public static void main(String[] args) {
    method testIncrement (line 24) | private static void testIncrement() {
    method increment (line 35) | private static void increment() {

FILE: src/com/winterbe/java8/samples/concurrent/Semaphore2.java
  class Semaphore2 (line 12) | public class Semaphore2 {
    method main (line 16) | public static void main(String[] args) {
    method doWork (line 25) | private static void doWork() {

FILE: src/com/winterbe/java8/samples/concurrent/Synchronized1.java
  class Synchronized1 (line 10) | public class Synchronized1 {
    method main (line 16) | public static void main(String[] args) {
    method testSyncIncrement (line 21) | private static void testSyncIncrement() {
    method testNonSyncIncrement (line 34) | private static void testNonSyncIncrement() {
    method incrementSync (line 47) | private static synchronized void incrementSync() {
    method increment (line 51) | private static void increment() {

FILE: src/com/winterbe/java8/samples/concurrent/Synchronized2.java
  class Synchronized2 (line 10) | public class Synchronized2 {
    method main (line 16) | public static void main(String[] args) {
    method testSyncIncrement (line 20) | private static void testSyncIncrement() {
    method incrementSync (line 33) | private static void incrementSync() {

FILE: src/com/winterbe/java8/samples/concurrent/Threads1.java
  class Threads1 (line 8) | public class Threads1 {
    method main (line 10) | public static void main(String[] args) {
    method test3 (line 16) | private static void test3() {
    method test2 (line 32) | private static void test2() {
    method test1 (line 48) | private static void test1() {

FILE: src/com/winterbe/java8/samples/lambda/Interface1.java
  class Interface1 (line 6) | public class Interface1 {
    type Formula (line 8) | interface Formula {
      method calculate (line 9) | double calculate(int a);
      method sqrt (line 11) | default double sqrt(int a) {
      method positive (line 15) | static int positive(int a) {
    method main (line 20) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/lambda/Lambda1.java
  class Lambda1 (line 12) | public class Lambda1 {
    method main (line 14) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/lambda/Lambda2.java
  class Lambda2 (line 6) | public class Lambda2 {
    type Converter (line 8) | @FunctionalInterface
      method convert (line 10) | T convert(F from);
    class Something (line 13) | static class Something {
      method startsWith (line 14) | String startsWith(String s) {
    type PersonFactory (line 19) | interface PersonFactory<P extends Person> {
      method create (line 20) | P create(String firstName, String lastName);
    method main (line 23) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/lambda/Lambda3.java
  class Lambda3 (line 17) | public class Lambda3 {
    type Fun (line 19) | @FunctionalInterface
      method foo (line 21) | void foo();
    method main (line 24) | public static void main(String[] args) throws Exception {

FILE: src/com/winterbe/java8/samples/lambda/Lambda4.java
  class Lambda4 (line 6) | public class Lambda4 {
    method testScopes (line 12) | void testScopes() {
    method main (line 37) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/lambda/Lambda5.java
  class Lambda5 (line 9) | public class Lambda5 {
    method main (line 12) | public static void main(String... args) {

FILE: src/com/winterbe/java8/samples/lambda/Person.java
  class Person (line 6) | public class Person {
    method Person (line 10) | public Person() {}
    method Person (line 12) | public Person(String firstName, String lastName) {

FILE: src/com/winterbe/java8/samples/misc/Annotations1.java
  class Annotations1 (line 12) | public class Annotations1 {
    class Person (line 30) | @Hint("hint1")
    method main (line 36) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/misc/CheckedFunctions.java
  class CheckedFunctions (line 12) | public final class CheckedFunctions {
    type CheckedConsumer (line 14) | @FunctionalInterface
      method accept (line 16) | void accept(T input) throws Exception;
    type CheckedPredicate (line 19) | @FunctionalInterface
      method test (line 21) | boolean test(T input) throws Exception;
    type CheckedFunction (line 24) | @FunctionalInterface
      method apply (line 26) | T apply(F input) throws Exception;
    method function (line 37) | public static <F, T> Function<F, T> function(CheckedFunction<F, T> fun...
    method predicate (line 58) | public static <T> Predicate<T> predicate(CheckedPredicate<T> predicate) {
    method consumer (line 79) | public static <T> Consumer<T> consumer(CheckedConsumer<T> consumer) {

FILE: src/com/winterbe/java8/samples/misc/Concurrency1.java
  class Concurrency1 (line 9) | public class Concurrency1 {
    method main (line 11) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/misc/Files1.java
  class Files1 (line 16) | public class Files1 {
    method main (line 18) | public static void main(String[] args) throws IOException {
    method testReaderLines (line 29) | private static void testReaderLines() throws IOException {
    method testWriter (line 40) | private static void testWriter() throws IOException {
    method testReader (line 47) | private static void testReader() throws IOException {
    method testWalk (line 54) | private static void testWalk() throws IOException {
    method testFind (line 66) | private static void testFind() throws IOException {
    method testList (line 79) | private static void testList() throws IOException {
    method testLines (line 90) | private static void testLines() throws IOException {
    method testReadWriteLines (line 99) | private static void testReadWriteLines() throws IOException {

FILE: src/com/winterbe/java8/samples/misc/Maps1.java
  class Maps1 (line 9) | public class Maps1 {
    method main (line 11) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/misc/Math1.java
  class Math1 (line 6) | public class Math1 {
    method main (line 8) | public static void main(String[] args) {
    method testUnsignedInt (line 13) | private static void testUnsignedInt() {
    method testMathExact (line 40) | private static void testMathExact() {

FILE: src/com/winterbe/java8/samples/misc/String1.java
  class String1 (line 10) | public class String1 {
    method main (line 12) | public static void main(String[] args) {
    method testChars (line 19) | private static void testChars() {
    method testPatternSplit (line 29) | private static void testPatternSplit() {
    method testPatternPredicate (line 38) | private static void testPatternPredicate() {
    method testJoin (line 45) | private static void testJoin() {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn1.java
  class Nashorn1 (line 17) | public class Nashorn1 {
    method main (line 19) | public static void main(String[] args) throws Exception {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn10.java
  class Nashorn10 (line 12) | public class Nashorn10 {
    method main (line 14) | public static void main(String[] args) throws ScriptException, NoSuchM...

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn11.java
  class Nashorn11 (line 15) | public class Nashorn11 {
    method main (line 17) | public static void main(String[] args) throws Exception {
    method test8 (line 28) | private static void test8() throws ScriptException {
    method test7 (line 47) | private static void test7() throws ScriptException {
    method test6 (line 66) | private static void test6() throws ScriptException {
    method test5 (line 86) | private static void test5() throws ScriptException {
    method test4 (line 106) | private static void test4() throws ScriptException {
    method test3 (line 121) | private static void test3() throws ScriptException {
    method test2 (line 138) | private static void test2() throws ScriptException {
    method test1 (line 147) | private static void test1() throws ScriptException {
    method createEngine (line 153) | private static NashornScriptEngine createEngine() {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn2.java
  class Nashorn2 (line 15) | public class Nashorn2 {
    method fun (line 17) | public static String fun(String name) {
    method fun2 (line 22) | public static void fun2(Object object) {
    method fun3 (line 26) | public static void fun3(ScriptObjectMirror mirror) {
    method fun4 (line 30) | public static void fun4(ScriptObjectMirror person) {
    method main (line 34) | public static void main(String[] args) throws Exception {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn3.java
  class Nashorn3 (line 11) | public class Nashorn3 {
    method main (line 13) | public static void main(String[] args) throws Exception {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn4.java
  class Nashorn4 (line 11) | public class Nashorn4 {
    method main (line 13) | public static void main(String[] args) throws Exception {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn5.java
  class Nashorn5 (line 12) | public class Nashorn5 {
    method main (line 14) | public static void main(String[] args) throws Exception {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn6.java
  class Nashorn6 (line 14) | public class Nashorn6 {
    method main (line 16) | public static void main(String[] args) throws Exception {
    method getProduct (line 32) | public static void getProduct(ScriptObjectMirror result) {

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn7.java
  class Nashorn7 (line 11) | public class Nashorn7 {
    class Person (line 13) | public static class Person {
      method getName (line 16) | public String getName() {
      method setName (line 20) | public void setName(String name) {
      method getLengthOfName (line 24) | public int getLengthOfName() {
    method main (line 29) | public static void main(String[] args) throws ScriptException, NoSuchM...

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn8.java
  class Nashorn8 (line 12) | public class Nashorn8 {
    method main (line 13) | public static void main(String[] args) throws ScriptException, NoSuchM...

FILE: src/com/winterbe/java8/samples/nashorn/Nashorn9.java
  class Nashorn9 (line 12) | public class Nashorn9 {
    method main (line 14) | public static void main(String[] args) throws ScriptException, NoSuchM...

FILE: src/com/winterbe/java8/samples/nashorn/Product.java
  class Product (line 6) | public class Product {
    method getValueOfGoods (line 12) | public double getValueOfGoods() {
    method setValueOfGoods (line 16) | public void setValueOfGoods(double valueOfGoods) {
    method getName (line 20) | public String getName() {
    method setName (line 24) | public void setName(String name) {
    method getPrice (line 28) | public double getPrice() {
    method setPrice (line 32) | public void setPrice(double price) {
    method getStock (line 36) | public int getStock() {
    method setStock (line 40) | public void setStock(int stock) {

FILE: src/com/winterbe/java8/samples/nashorn/SuperRunner.java
  class SuperRunner (line 6) | public class SuperRunner implements Runnable {
    method run (line 8) | @Override

FILE: src/com/winterbe/java8/samples/stream/Optional1.java
  class Optional1 (line 8) | public class Optional1 {
    method main (line 10) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Optional2.java
  class Optional2 (line 13) | public class Optional2 {
    class Outer (line 15) | static class Outer {
      method getNested (line 18) | public Nested getNested() {
    class Nested (line 23) | static class Nested {
      method getInner (line 26) | public Inner getInner() {
    class Inner (line 31) | static class Inner {
      method getFoo (line 34) | public String getFoo() {
    method main (line 39) | public static void main(String[] args) {
    method resolve (line 45) | public static <T> Optional<T> resolve(Supplier<T> resolver) {
    method test3 (line 55) | private static void test3() {
    method test2 (line 61) | private static void test2() {
    method test1 (line 69) | private static void test1() {

FILE: src/com/winterbe/java8/samples/stream/Streams1.java
  class Streams1 (line 10) | public class Streams1 {
    method main (line 12) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Streams10.java
  class Streams10 (line 14) | public class Streams10 {
    class Person (line 16) | static class Person {
      method Person (line 20) | Person(String name, int age) {
      method toString (line 25) | @Override
    method main (line 31) | public static void main(String[] args) {
    method test1 (line 50) | private static void test1(List<Person> persons) {
    method test2 (line 60) | private static void test2(List<Person> persons) {
    method test3 (line 73) | private static void test3(List<Person> persons) {
    method test4 (line 81) | private static void test4(List<Person> persons) {
    method test5 (line 91) | private static void test5(List<Person> persons) {
    method test6 (line 102) | private static void test6(List<Person> persons) {
    method test7 (line 114) | private static void test7(List<Person> persons) {
    method test8 (line 129) | private static void test8(List<Person> persons) {
    method test9 (line 156) | private static void test9(List<Person> persons) {

FILE: src/com/winterbe/java8/samples/stream/Streams11.java
  class Streams11 (line 9) | public class Streams11 {
    class Person (line 11) | static class Person {
      method Person (line 15) | Person(String name, int age) {
      method toString (line 20) | @Override
    method main (line 26) | public static void main(String[] args) {
    method test1 (line 42) | private static void test1(List<Person> persons) {
    method test2 (line 49) | private static void test2(List<Person> persons) {
    method test3 (line 62) | private static void test3(List<Person> persons) {
    method test4 (line 70) | private static void test4(List<Person> persons) {
    method test5 (line 86) | private static void test5(List<Person> persons) {
    method test6 (line 102) | private static void test6(List<Person> persons) {

FILE: src/com/winterbe/java8/samples/stream/Streams12.java
  class Streams12 (line 13) | public class Streams12 {
    method main (line 15) | public static void main(String[] args) {
    method test4 (line 24) | private static void test4() {
    method test3 (line 50) | private static void test3(List<String> strings) {
    method test2 (line 68) | private static void test2(List<String> strings) {
    method test1 (line 82) | private static void test1() {

FILE: src/com/winterbe/java8/samples/stream/Streams13.java
  class Streams13 (line 10) | public class Streams13 {
    method main (line 12) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Streams2.java
  class Streams2 (line 9) | public class Streams2 {
    method main (line 11) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Streams3.java
  class Streams3 (line 11) | public class Streams3 {
    method sortSequential (line 15) | public static void sortSequential() {
    method sortParallel (line 35) | public static void sortParallel() {
    method main (line 55) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Streams4.java
  class Streams4 (line 9) | public class Streams4 {
    method main (line 11) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Streams5.java
  class Streams5 (line 13) | public class Streams5 {
    method main (line 15) | public static void main(String[] args) {
    method test8 (line 29) | private static void test8(List<String> stringCollection) {
    method test7 (line 40) | private static void test7(List<String> stringCollection) {
    method test6 (line 50) | private static void test6(List<String> stringCollection) {
    method test5 (line 63) | private static void test5(List<String> stringCollection) {
    method test4 (line 82) | private static void test4(List<String> stringCollection) {
    method test3 (line 100) | private static void test3(List<String> stringCollection) {
    method test2 (line 114) | private static void test2(List<String> stringCollection) {
    method test1 (line 128) | private static void test1(List<String> stringCollection) {

FILE: src/com/winterbe/java8/samples/stream/Streams6.java
  class Streams6 (line 12) | public class Streams6 {
    method main (line 14) | public static void main(String[] args) throws IOException {
    method test4 (line 21) | private static void test4() {
    method test3 (line 29) | private static void test3() {
    method test2 (line 36) | private static void test2() {
    method test1 (line 50) | private static void test1() {

FILE: src/com/winterbe/java8/samples/stream/Streams7.java
  class Streams7 (line 10) | public class Streams7 {
    class Foo (line 12) | static class Foo {
      method Foo (line 16) | Foo(String name) {
    class Bar (line 21) | static class Bar {
      method Bar (line 24) | Bar(String name) {
    method main (line 29) | public static void main(String[] args) {
    method test2 (line 34) | static void test2() {
    method test1 (line 44) | static void test1() {

FILE: src/com/winterbe/java8/samples/stream/Streams8.java
  class Streams8 (line 10) | public class Streams8 {
    method main (line 12) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/stream/Streams9.java
  class Streams9 (line 8) | public class Streams9 {
    method main (line 10) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/time/LocalDate1.java
  class LocalDate1 (line 14) | public class LocalDate1 {
    method main (line 16) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/time/LocalDateTime1.java
  class LocalDateTime1 (line 15) | public class LocalDateTime1 {
    method main (line 17) | public static void main(String[] args) {

FILE: src/com/winterbe/java8/samples/time/LocalTime1.java
  class LocalTime1 (line 16) | public class LocalTime1 {
    method main (line 18) | public static void main(String[] args) {
Condensed preview — 82 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (153K chars).
[
  {
    "path": ".gitignore",
    "chars": 32,
    "preview": ".DS_Store\n.idea\n*.iml\nout\n/bin/\n"
  },
  {
    "path": "LICENSE",
    "chars": 1086,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2023 Benjamin Winterberg\n\nPermission is hereby granted, free of charge, to any pers"
  },
  {
    "path": "README.md",
    "chars": 29149,
    "preview": "# Modern Java - A Guide to Java 8\n_This article was originally posted on [my blog](http://winterbe.com/posts/2014/03/16/"
  },
  {
    "path": "res/nashorn1.js",
    "chars": 230,
    "preview": "var fun1 = function(name) {\n    print('Hi there from Javascript, ' + name);\n    return \"greetings from javascript\";\n};\n\n"
  },
  {
    "path": "res/nashorn10.js",
    "chars": 558,
    "preview": "var results = [];\n\nvar Context = function () {\n    this.foo = 'bar';\n};\n\nContext.prototype.testArgs = function () {\n    "
  },
  {
    "path": "res/nashorn2.js",
    "chars": 787,
    "preview": "var Nashorn2 = Java.type('com.winterbe.java8.samples.nashorn.Nashorn2');\nvar result = Nashorn2.fun('John Doe');\nprint('\\"
  },
  {
    "path": "res/nashorn3.js",
    "chars": 2115,
    "preview": "print('------------------');\nprint('IntArray:');\n\nvar IntArray = Java.type('int[]');\n\nvar array = new IntArray(5);\narray"
  },
  {
    "path": "res/nashorn4.js",
    "chars": 1609,
    "preview": "// function literal with no braces\n\nfunction sqr(x) x * x;\n\nprint(sqr(3));\n\n\n// for each\n\nvar array = [1, 2, 3, 4];\nfor "
  },
  {
    "path": "res/nashorn5.js",
    "chars": 508,
    "preview": "function Product(name) {\n    this.name = name;\n}\n\nProduct.prototype.stock = 0;\nProduct.prototype.price = 0;\nProduct.prot"
  },
  {
    "path": "res/nashorn6.js",
    "chars": 1381,
    "preview": "load('http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.6.0/underscore-min.js');\nload('http://cdnjs.cloudflare.com/a"
  },
  {
    "path": "res/nashorn7.js",
    "chars": 555,
    "preview": "function sqrt(x)  x * x\nprint(sqrt(3));\n\nvar array = [1, 2, 3, 4];\nfor each (var num in array) print(num);\n\nvar runnable"
  },
  {
    "path": "res/nashorn8.js",
    "chars": 336,
    "preview": "var evaluate1 = function () {\n    (function () {\n        print(eval(\"this\"));\n    }).call(this);\n};\n\nvar evaluate2 = fun"
  },
  {
    "path": "res/nashorn9.js",
    "chars": 189,
    "preview": "var size = 100000;\n\nvar testPerf = function () {\n    var result = Math.floor(Math.random() * size) + 1;\n    for (var i ="
  },
  {
    "path": "src/com/winterbe/java11/HttpClientExamples.java",
    "chars": 3084,
    "preview": "package com.winterbe.java11;\n\nimport java.io.IOException;\nimport java.net.Authenticator;\nimport java.net.PasswordAuthent"
  },
  {
    "path": "src/com/winterbe/java11/LocalVariableSyntax.java",
    "chars": 871,
    "preview": "package com.winterbe.java11;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util."
  },
  {
    "path": "src/com/winterbe/java11/Misc.java",
    "chars": 2354,
    "preview": "package com.winterbe.java11;\n\nimport java.io.File;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport j"
  },
  {
    "path": "src/com/winterbe/java11/dummy.txt",
    "chars": 6,
    "preview": "Foobar"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Atomic1.java",
    "chars": 1926,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java",
    "chars": 550,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.CompletableFuture;\nimport java.util.concurre"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java",
    "chars": 2418,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurre"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java",
    "chars": 895,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Executors1.java",
    "chars": 1431,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Executors2.java",
    "chars": 2288,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutionException;\nimport java.util.concurr"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Executors3.java",
    "chars": 3396,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.concurr"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Lock1.java",
    "chars": 981,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Lock2.java",
    "chars": 947,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Lock3.java",
    "chars": 1232,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurr"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Lock4.java",
    "chars": 1167,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.concurr"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Lock5.java",
    "chars": 1312,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Lock6.java",
    "chars": 1045,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java",
    "chars": 879,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/LongAdder1.java",
    "chars": 1182,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Semaphore1.java",
    "chars": 1269,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Semaphore2.java",
    "chars": 1213,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Synchronized1.java",
    "chars": 1309,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Synchronized2.java",
    "chars": 884,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent"
  },
  {
    "path": "src/com/winterbe/java8/samples/concurrent/Threads1.java",
    "chars": 1571,
    "preview": "package com.winterbe.java8.samples.concurrent;\n\nimport java.util.concurrent.TimeUnit;\n\n/**\n * @author Benjamin Winterber"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Interface1.java",
    "chars": 761,
    "preview": "package com.winterbe.java8.samples.lambda;\n\n/**\n * @author Benjamin Winterberg\n */\npublic class Interface1 {\n\n    interf"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Lambda1.java",
    "chars": 1286,
    "preview": "package com.winterbe.java8.samples.lambda;\n\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Comp"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Lambda2.java",
    "chars": 1337,
    "preview": "package com.winterbe.java8.samples.lambda;\n\n/**\n * @author Benjamin Winterberg\n */\npublic class Lambda2 {\n\n    @Function"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Lambda3.java",
    "chars": 2041,
    "preview": "package com.winterbe.java8.samples.lambda;\n\nimport java.util.Comparator;\nimport java.util.Objects;\nimport java.util.UUID"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Lambda4.java",
    "chars": 948,
    "preview": "package com.winterbe.java8.samples.lambda;\n\n/**\n * @author Benjamin Winterberg\n */\npublic class Lambda4 {\n\n    static in"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Lambda5.java",
    "chars": 848,
    "preview": "package com.winterbe.java8.samples.lambda;\n\nimport java.util.HashMap;\nimport java.util.function.BiConsumer;\n\n/**\n * Crea"
  },
  {
    "path": "src/com/winterbe/java8/samples/lambda/Person.java",
    "chars": 317,
    "preview": "package com.winterbe.java8.samples.lambda;\n\n/**\n* @author Benjamin Winterberg\n*/\npublic class Person {\n    public String"
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/Annotations1.java",
    "chars": 1095,
    "preview": "package com.winterbe.java8.samples.misc;\n\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Repeatabl"
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/CheckedFunctions.java",
    "chars": 2449,
    "preview": "package com.winterbe.java8.samples.misc;\n\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport"
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/Concurrency1.java",
    "chars": 986,
    "preview": "package com.winterbe.java8.samples.misc;\n\nimport java.util.UUID;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * "
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/Files1.java",
    "chars": 3445,
    "preview": "package com.winterbe.java8.samples.misc;\n\nimport java.io.BufferedReader;\nimport java.io.BufferedWriter;\nimport java.io.I"
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/Maps1.java",
    "chars": 1416,
    "preview": "package com.winterbe.java8.samples.misc;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\n/**\n * @author Benjamin Winte"
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/Math1.java",
    "chars": 1482,
    "preview": "package com.winterbe.java8.samples.misc;\n\n/**\n * @author Benjamin Winterberg\n */\npublic class Math1 {\n\n    public static"
  },
  {
    "path": "src/com/winterbe/java8/samples/misc/String1.java",
    "chars": 1378,
    "preview": "package com.winterbe.java8.samples.misc;\n\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\nimport jav"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn1.java",
    "chars": 999,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport com.winterbe.java8.samples.lambda.Person;\n\nimport javax.script.Invoc"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn10.java",
    "chars": 814,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport jdk.nashorn.api.scripting.NashornScriptEngine;\n\nimport javax.script."
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn11.java",
    "chars": 5783,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport jdk.nashorn.api.scripting.NashornScriptEngine;\n\nimport javax.script."
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn2.java",
    "chars": 1115,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport jdk.nashorn.api.scripting.ScriptObjectMirror;\n\nimport javax.script.S"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn3.java",
    "chars": 434,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport javax.script.ScriptEngine;\nimport javax.script.ScriptEngineManager;\n"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn4.java",
    "chars": 447,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport javax.script.ScriptEngine;\nimport javax.script.ScriptEngineManager;\n"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn5.java",
    "chars": 779,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport javax.script.Invocable;\nimport javax.script.ScriptEngine;\nimport jav"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn6.java",
    "chars": 1066,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport jdk.nashorn.api.scripting.ScriptObjectMirror;\n\nimport javax.script.I"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn7.java",
    "chars": 1122,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport javax.script.Invocable;\nimport javax.script.ScriptEngine;\nimport jav"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn8.java",
    "chars": 919,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport com.winterbe.java8.samples.lambda.Person;\nimport jdk.nashorn.api.scr"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Nashorn9.java",
    "chars": 927,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\nimport jdk.nashorn.api.scripting.NashornScriptEngine;\n\nimport javax.script."
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/Product.java",
    "chars": 789,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\n/**\n * @author Benjamin Winterberg\n */\npublic class Product {\n    private S"
  },
  {
    "path": "src/com/winterbe/java8/samples/nashorn/SuperRunner.java",
    "chars": 219,
    "preview": "package com.winterbe.java8.samples.nashorn;\n\n/**\n * @author Benjamin Winterberg\n */\npublic class SuperRunner implements "
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Optional1.java",
    "chars": 473,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Optional;\n\n/**\n * @author Benjamin Winterberg\n */\npublic cl"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Optional2.java",
    "chars": 1810,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Optional;\nimport java.util.function.Supplier;\n\n/**\n * Examp"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams1.java",
    "chars": 2435,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams10.java",
    "chars": 5517,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Arrays;\nimport java.util.IntSummaryStatistics;\nimport java."
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams11.java",
    "chars": 3425,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * @author Benjamin Win"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams12.java",
    "chars": 2810,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams13.java",
    "chars": 709,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.security.SecureRandom;\nimport java.util.Arrays;\nimport java.util"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams2.java",
    "chars": 781,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\n/**\n * @author Benjamin "
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams3.java",
    "chars": 1512,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.UUID;\nim"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams4.java",
    "chars": 902,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.OptionalInt;\nimport java.util.stream.IntStream;\n\n/**\n * @au"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams5.java",
    "chars": 4137,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Arrays;\nimport java.util.List;\nimport java.util.function.Su"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams6.java",
    "chars": 1249,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.io.IOException;\nimport java.math.BigDecimal;\nimport java.util.Ar"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams7.java",
    "chars": 1402,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.stream.I"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams8.java",
    "chars": 975,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Arrays;\nimport java.util.stream.IntStream;\nimport java.util"
  },
  {
    "path": "src/com/winterbe/java8/samples/stream/Streams9.java",
    "chars": 437,
    "preview": "package com.winterbe.java8.samples.stream;\n\nimport java.util.Arrays;\n\n/**\n * @author Benjamin Winterberg\n */\npublic clas"
  },
  {
    "path": "src/com/winterbe/java8/samples/time/LocalDate1.java",
    "chars": 1159,
    "preview": "package com.winterbe.java8.samples.time;\n\nimport java.time.DayOfWeek;\nimport java.time.LocalDate;\nimport java.time.Month"
  },
  {
    "path": "src/com/winterbe/java8/samples/time/LocalDateTime1.java",
    "chars": 1412,
    "preview": "package com.winterbe.java8.samples.time;\n\nimport java.time.DayOfWeek;\nimport java.time.Instant;\nimport java.time.LocalDa"
  },
  {
    "path": "src/com/winterbe/java8/samples/time/LocalTime1.java",
    "chars": 1845,
    "preview": "package com.winterbe.java8.samples.time;\n\nimport java.time.Clock;\nimport java.time.Instant;\nimport java.time.LocalTime;\n"
  }
]

About this extraction

This page contains the full source code of the winterbe/java8-tutorial GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 82 files (137.6 KB), approximately 34.0k tokens, and a symbol index with 300 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!