diff --git a/.gitignore b/.gitignore index 77642f01..f911407f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .DS_Store .idea *.iml -out \ No newline at end of file +out +/bin/ diff --git a/LICENSE b/LICENSE index 3e09223f..cc53a543 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014 Benjamin Winterberg +Copyright (c) 2023 Benjamin Winterberg Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file +SOFTWARE. diff --git a/README.md b/README.md index 012224ab..e9caeed4 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,814 @@ -Java 8 Tutorial -============== +# 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/)._ -This repository contains all code samples from the Java 8 Tutorials of my blog: +> **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).** -- http://winterbe.com/posts/2014/03/16/java-8-tutorial/ -- http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/ -- http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/ +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!** -I'm adding new samples from time to time, but feel free to fork and try it yourself. +--- +

+ ★★★ Like this project? Leave a star, follow on Twitter or donate to support my work. Thanks! ★★★ +

-Contribute -============== +--- -Want to share your own java 8 code samples? Feel free to fork the repo and send me a pull request. +## 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 names = Arrays.asList("peter", "anna", "mike", "xenia"); + +Collections.sort(names, new Comparator() { + @Override + public int compare(String a, String b) { + return b.compareTo(a); + } +}); +``` + +The static utility method `Collections.sort` accepts a list and a comparator in order to sort the elements of the given list. You often find yourself creating anonymous comparators and pass them to the sort method. + +Instead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, **lambda expressions**: + +```java +Collections.sort(names, (String a, String b) -> { + return b.compareTo(a); +}); +``` + +As you can see the code is much shorter and easier to read. But it gets even shorter: + +```java +Collections.sort(names, (String a, String b) -> b.compareTo(a)); +``` + +For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even 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 { + T convert(F from); +} +``` + +```java +Converter converter = (from) -> Integer.valueOf(from); +Integer converted = converter.convert("123"); +System.out.println(converted); // 123 +``` + +Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be omitted. + + +## Method and Constructor References + +The above example code can be further simplified by utilizing static method references: + +```java +Converter converter = Integer::valueOf; +Integer converted = converter.convert("123"); +System.out.println(converted); // 123 +``` + +Java 8 enables you to pass references of methods or constructors via the `::` keyword. The above example shows how to reference a static method. But we can also reference object methods: + +```java +class Something { + String startsWith(String s) { + return String.valueOf(s.charAt(0)); + } +} +``` + +```java +Something something = new Something(); +Converter converter = something::startsWith; +String converted = converter.convert("Java"); +System.out.println(converted); // "J" +``` + +Let's see how the `::` keyword works for constructors. First we define an example 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 create(String firstName, String lastName); +} +``` + +Instead of implementing the factory manually, we glue everything together via constructor references: + +```java +PersonFactory personFactory = Person::new; +Person person = personFactory.create("Peter", "Parker"); +``` + +We create a reference to the Person constructor via `Person::new`. The Java compiler automatically chooses the right constructor by matching the signature of `PersonFactory.create`. + +## Lambda Scopes + +Accessing outer scope variables from lambda expressions is very similar to anonymous objects. You can access final variables from the local outer scope as well as instance fields and static variables. + +### Accessing local variables + +We can read final local variables from the outer scope of lambda expressions: + +```java +final int num = 1; +Converter stringConverter = + (from) -> String.valueOf(from + num); + +stringConverter.convert(2); // 3 +``` + +But different to anonymous objects the variable `num` does not have to be declared final. This code is also valid: + +```java +int num = 1; +Converter stringConverter = + (from) -> String.valueOf(from + num); + +stringConverter.convert(2); // 3 +``` + +However `num` must be implicitly final for the code to compile. The following code does **not** compile: + +```java +int num = 1; +Converter stringConverter = + (from) -> String.valueOf(from + num); +num = 3; +``` + +Writing to `num` from within the lambda expression is also prohibited. + +### Accessing fields and static variables + +In 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 stringConverter1 = (from) -> { + outerNum = 23; + return String.valueOf(from); + }; + + Converter stringConverter2 = (from) -> { + outerStaticNum = 72; + return String.valueOf(from); + }; + } +} +``` + +### Accessing Default Interface Methods + +Remember the formula example from the first section? Interface `Formula` defines a default method `sqrt` which can be accessed from each formula instance including anonymous objects. This does not work with lambda expressions. + +Default methods **cannot** be accessed from within lambda expressions. The following code does not compile: + +```java +Formula formula = (a) -> sqrt(a * 100); +``` + + +## Built-in Functional Interfaces + +The JDK 1.8 API contains many built-in functional interfaces. Some of them are well known from older versions of Java like `Comparator` or `Runnable`. Those existing interfaces are extended to enable Lambda support via the `@FunctionalInterface` annotation. + +But the Java 8 API is also full of new functional interfaces to make your life easier. Some of those new interfaces are well known from the [Google Guava](https://code.google.com/p/guava-libraries/) library. Even if you're familiar with this library you should keep a close eye on how those interfaces are extended by some useful method extensions. + +### Predicates + +Predicates are boolean-valued functions of one argument. The interface contains various default methods for composing predicates to complex logical terms (and, or, negate) + +```java +Predicate predicate = (s) -> s.length() > 0; + +predicate.test("foo"); // true +predicate.negate().test("foo"); // false + +Predicate nonNull = Objects::nonNull; +Predicate isNull = Objects::isNull; + +Predicate isEmpty = String::isEmpty; +Predicate isNotEmpty = isEmpty.negate(); +``` + +### Functions + +Functions accept one argument and produce a result. Default methods can be used to chain multiple functions together (compose, andThen). + +```java +Function toInteger = Integer::valueOf; +Function backToString = toInteger.andThen(String::valueOf); + +backToString.apply("123"); // "123" +``` + +### Suppliers + +Suppliers produce a result of a given generic type. Unlike Functions, Suppliers don't accept arguments. + +```java +Supplier personSupplier = Person::new; +personSupplier.get(); // new Person +``` + +### Consumers + +Consumers represent operations to be performed on a single input argument. + +```java +Consumer greeter = (p) -> System.out.println("Hello, " + p.firstName); +greeter.accept(new Person("Luke", "Skywalker")); +``` + +### Comparators + +Comparators are well known from older versions of Java. Java 8 adds various default methods to the interface. + +```java +Comparator comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); + +Person p1 = new Person("John", "Doe"); +Person p2 = new Person("Alice", "Wonderland"); + +comparator.compare(p1, p2); // > 0 +comparator.reversed().compare(p1, p2); // < 0 +``` + +## Optionals + +Optionals are not functional interfaces, 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 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 stringCollection = new ArrayList<>(); +stringCollection.add("ddd2"); +stringCollection.add("aaa2"); +stringCollection.add("bbb1"); +stringCollection.add("aaa1"); +stringCollection.add("bbb3"); +stringCollection.add("ccc"); +stringCollection.add("bbb2"); +stringCollection.add("ddd1"); +``` + +Collections in Java 8 are extended so you can simply create streams either by calling `Collection.stream()` or `Collection.parallelStream()`. The following sections explain the most common stream operations. + +### Filter + +Filter accepts a predicate to filter all elements of the stream. This operation is _intermediate_ which enables us to call another stream operation (`forEach`) on the result. ForEach accepts a consumer to be executed for each element in the filtered stream. ForEach is a terminal operation. It's `void`, so we cannot call another stream operation. + +```java +stringCollection + .stream() + .filter((s) -> s.startsWith("a")) + .forEach(System.out::println); + +// "aaa2", "aaa1" +``` + +### Sorted + +Sorted is an _intermediate_ operation which returns a sorted view of the stream. The elements are sorted in natural order unless you pass a custom `Comparator`. + +```java +stringCollection + .stream() + .sorted() + .filter((s) -> s.startsWith("a")) + .forEach(System.out::println); + +// "aaa1", "aaa2" +``` + +Keep in mind that `sorted` does only create a sorted view of the stream without manipulating the ordering of the backed collection. The ordering of `stringCollection` is untouched: + +```java +System.out.println(stringCollection); +// ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1 +``` + +### Map + +The _intermediate_ operation `map` converts each element into another object via the given function. The following example converts each string into an upper-cased string. But you can also use `map` to transform each object into another type. The generic type of the resulting stream depends on the generic type of the function you pass to `map`. + +```java +stringCollection + .stream() + .map(String::toUpperCase) + .sorted((a, b) -> b.compareTo(a)) + .forEach(System.out::println); + +// "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1" +``` + +### Match + +Various matching operations can be used to check whether a certain predicate matches the stream. All of those operations are _terminal_ and return a boolean result. + +```java +boolean anyStartsWithA = + stringCollection + .stream() + .anyMatch((s) -> s.startsWith("a")); + +System.out.println(anyStartsWithA); // true + +boolean allStartsWithA = + stringCollection + .stream() + .allMatch((s) -> s.startsWith("a")); + +System.out.println(allStartsWithA); // false + +boolean noneStartsWithZ = + stringCollection + .stream() + .noneMatch((s) -> s.startsWith("z")); + +System.out.println(noneStartsWithZ); // true +``` + +#### Count + +Count is a _terminal_ operation returning the number of elements in the stream as a `long`. + +```java +long startsWithB = + stringCollection + .stream() + .filter((s) -> s.startsWith("b")) + .count(); + +System.out.println(startsWithB); // 3 +``` + + +### Reduce + +This _terminal_ operation performs a reduction on the elements of the stream with the given function. The result is an `Optional` holding the reduced value. + +```java +Optional reduced = + stringCollection + .stream() + .sorted() + .reduce((s1, s2) -> s1 + "#" + s2); + +reduced.ifPresent(System.out::println); +// "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2" +``` + +## Parallel Streams + +As mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed 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 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 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! diff --git a/res/nashorn10.js b/res/nashorn10.js new file mode 100644 index 00000000..9c572d5c --- /dev/null +++ b/res/nashorn10.js @@ -0,0 +1,29 @@ +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); +}; \ No newline at end of file diff --git a/res/nashorn2.js b/res/nashorn2.js index f9eafe67..32bdd0f6 100644 --- a/res/nashorn2.js +++ b/res/nashorn2.js @@ -1,4 +1,4 @@ -var Nashorn2 = Java.type('com.winterbe.java8.Nashorn2'); +var Nashorn2 = Java.type('com.winterbe.java8.samples.nashorn.Nashorn2'); var result = Nashorn2.fun('John Doe'); print('\n' + result); diff --git a/res/nashorn4.js b/res/nashorn4.js index c4c9a1fe..461ebca4 100644 --- a/res/nashorn4.js +++ b/res/nashorn4.js @@ -74,7 +74,7 @@ print(Object.prototype.toString.call(javaArray)); // calling super -var SuperRunner = Java.type('com.winterbe.java8.SuperRunner'); +var SuperRunner = Java.type('com.winterbe.java8.samples.nashorn.SuperRunner'); var Runner = Java.extend(SuperRunner); var runner = new Runner() { diff --git a/res/nashorn6.js b/res/nashorn6.js index 1db7311a..f4bae9a5 100644 --- a/res/nashorn6.js +++ b/res/nashorn6.js @@ -33,7 +33,7 @@ product.set('price', 3.99); // pass backbone model to java method -var Nashorn6 = Java.type('com.winterbe.java8.Nashorn6'); +var Nashorn6 = Java.type('com.winterbe.java8.samples.nashorn.Nashorn6'); Nashorn6.getProduct(product.attributes); diff --git a/res/nashorn7.js b/res/nashorn7.js new file mode 100644 index 00000000..9246f163 --- /dev/null +++ b/res/nashorn7.js @@ -0,0 +1,27 @@ +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); + }); \ No newline at end of file diff --git a/res/nashorn8.js b/res/nashorn8.js new file mode 100644 index 00000000..d7bb6a67 --- /dev/null +++ b/res/nashorn8.js @@ -0,0 +1,18 @@ +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); +}; \ No newline at end of file diff --git a/res/nashorn9.js b/res/nashorn9.js new file mode 100644 index 00000000..e60e2b06 --- /dev/null +++ b/res/nashorn9.js @@ -0,0 +1,9 @@ +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; +}; \ No newline at end of file diff --git a/src/com/winterbe/java11/HttpClientExamples.java b/src/com/winterbe/java11/HttpClientExamples.java new file mode 100644 index 00000000..7342b1de --- /dev/null +++ b/src/com/winterbe/java11/HttpClientExamples.java @@ -0,0 +1,78 @@ +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 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 + } + +} diff --git a/src/com/winterbe/java11/LocalVariableSyntax.java b/src/com/winterbe/java11/LocalVariableSyntax.java new file mode 100644 index 00000000..e2a60906 --- /dev/null +++ b/src/com/winterbe/java11/LocalVariableSyntax.java @@ -0,0 +1,37 @@ +package com.winterbe.java11; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +public class LocalVariableSyntax { + + public static void main(String[] args) { + var text = "Banana"; +// Incompatible types: +// text = 1; + + +// Cannot infer type: +// var a; +// var nothing = null; +// var bla = () -> System.out.println("Hallo"); +// var method = LocalVariableSyntax::someMethod; + + var list1 = new ArrayList<>(); // ArrayList + + var list2 = new ArrayList>>(); + + for (var current : list2) { + // current is of type: Map> + System.out.println(current); + } + + Predicate predicate1 = (@Deprecated var a) -> false; + + } + + void someMethod() {} + +} diff --git a/src/com/winterbe/java11/Misc.java b/src/com/winterbe/java11/Misc.java new file mode 100644 index 00000000..e343dec7 --- /dev/null +++ b/src/com/winterbe/java11/Misc.java @@ -0,0 +1,69 @@ +package com.winterbe.java11; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Misc { + + @Deprecated(forRemoval = true) + String foo; + + public static void main(String[] args) throws IOException { + collections(); + strings(); + optionals(); + inputStreams(); + streams(); + } + + private static void streams() { + System.out.println(Stream.ofNullable(null).count()); // 0 + System.out.println(Stream.of(1, 2, 3, 2, 1) + .dropWhile(n -> n < 3) + .collect(Collectors.toList())); // [3, 2, 1] + System.out.println(Stream.of(1, 2, 3, 2, 1) + .takeWhile(n -> n < 3) + .collect(Collectors.toList())); // [1, 2] + } + + private static void inputStreams() throws IOException { + var classLoader = ClassLoader.getSystemClassLoader(); + var inputStream = classLoader.getResourceAsStream("com/winterbe/java11/dummy.txt"); + var tempFile = File.createTempFile("dummy-copy", "txt"); + try (var outputStream = new FileOutputStream(tempFile)) { + inputStream.transferTo(outputStream); + } + System.out.println(tempFile.length()); + } + + private static void optionals() { + System.out.println(Optional.of("foo").orElseThrow()); // foo + System.out.println(Optional.ofNullable(null).or(() -> Optional.of("bar")).get()); // bar + System.out.println(Optional.of("foo").stream().count()); // 1 + } + + private static void strings() { + System.out.println(" ".isBlank()); + System.out.println(" Foo Bar ".strip()); // "Foo Bar" + System.out.println(" Foo Bar ".stripTrailing()); // " Foo Bar" + System.out.println(" Foo Bar ".stripLeading()); // "Foo Bar " + System.out.println("Java".repeat(3)); // "JavaJavaJava" + System.out.println("A\nB\nC".lines().count()); // 3 + } + + private static void collections() { + var list = List.of("A", "B", "C"); + var copy = List.copyOf(list); + System.out.println(list == copy); // true + + var map = Map.of("A", 1, "B", 2); + System.out.println(map); + } + +} diff --git a/src/com/winterbe/java11/dummy.txt b/src/com/winterbe/java11/dummy.txt new file mode 100644 index 00000000..5eced957 --- /dev/null +++ b/src/com/winterbe/java11/dummy.txt @@ -0,0 +1 @@ +Foobar \ No newline at end of file diff --git a/src/com/winterbe/java8/Person.java b/src/com/winterbe/java8/Person.java deleted file mode 100644 index 86c9bdec..00000000 --- a/src/com/winterbe/java8/Person.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.winterbe.java8; - -/** -* @author Benjamin Winterberg -*/ -class Person { - String firstName; - String lastName; - - Person() {} - - Person(String firstName, String lastName) { - this.firstName = firstName; - this.lastName = lastName; - } -} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/concurrent/Atomic1.java b/src/com/winterbe/java8/samples/concurrent/Atomic1.java new file mode 100644 index 00000000..0f9d3cba --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -0,0 +1,70 @@ +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()); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java b/src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java new file mode 100644 index 00000000..82be5d75 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java @@ -0,0 +1,22 @@ +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 future = new CompletableFuture<>(); + + future.complete("42"); + + future + .thenAccept(System.out::println) + .thenAccept(v -> System.out.println("done")); + + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java new file mode 100644 index 00000000..4acf79ab --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java @@ -0,0 +1,77 @@ +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 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 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 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()); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java new file mode 100644 index 00000000..86cfee8d --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java @@ -0,0 +1,35 @@ +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); + } + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Executors1.java b/src/com/winterbe/java8/samples/concurrent/Executors1.java new file mode 100644 index 00000000..9762938d --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Executors1.java @@ -0,0 +1,49 @@ +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"); + } + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/Executors2.java b/src/com/winterbe/java8/samples/concurrent/Executors2.java new file mode 100644 index 00000000..33dda88e --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Executors2.java @@ -0,0 +1,77 @@ +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 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 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 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(); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Executors3.java b/src/com/winterbe/java8/samples/concurrent/Executors3.java new file mode 100644 index 00000000..75e60377 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Executors3.java @@ -0,0 +1,108 @@ +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> 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 callable(String result, long sleepSeconds) { + return () -> { + TimeUnit.SECONDS.sleep(sleepSeconds); + return result; + }; + } + + private static void test4() throws InterruptedException { + ExecutorService executor = Executors.newWorkStealingPool(); + + List> 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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lock1.java b/src/com/winterbe/java8/samples/concurrent/Lock1.java new file mode 100644 index 00000000..d96eba3a --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock1.java @@ -0,0 +1,45 @@ +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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lock2.java b/src/com/winterbe/java8/samples/concurrent/Lock2.java new file mode 100644 index 00000000..12757908 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock2.java @@ -0,0 +1,36 @@ +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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lock3.java b/src/com/winterbe/java8/samples/concurrent/Lock3.java new file mode 100644 index 00000000..5e24a49b --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock3.java @@ -0,0 +1,47 @@ +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 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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lock4.java b/src/com/winterbe/java8/samples/concurrent/Lock4.java new file mode 100644 index 00000000..4061a694 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock4.java @@ -0,0 +1,46 @@ +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 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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lock5.java b/src/com/winterbe/java8/samples/concurrent/Lock5.java new file mode 100644 index 00000000..79802230 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock5.java @@ -0,0 +1,44 @@ +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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Lock6.java b/src/com/winterbe/java8/samples/concurrent/Lock6.java new file mode 100644 index 00000000..a518b568 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock6.java @@ -0,0 +1,39 @@ +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); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java b/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java new file mode 100644 index 00000000..fa000a1b --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java @@ -0,0 +1,31 @@ +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()); + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/LongAdder1.java b/src/com/winterbe/java8/samples/concurrent/LongAdder1.java new file mode 100644 index 00000000..98cb1843 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/LongAdder1.java @@ -0,0 +1,43 @@ +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()); + } +} diff --git a/src/com/winterbe/java8/samples/concurrent/Semaphore1.java b/src/com/winterbe/java8/samples/concurrent/Semaphore1.java new file mode 100644 index 00000000..17f4c51a --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Semaphore1.java @@ -0,0 +1,51 @@ +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(); + } + } + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Semaphore2.java b/src/com/winterbe/java8/samples/concurrent/Semaphore2.java new file mode 100644 index 00000000..23380594 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Semaphore2.java @@ -0,0 +1,44 @@ +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(); + } + } + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Synchronized1.java b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java new file mode 100644 index 00000000..c2a4e612 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java @@ -0,0 +1,55 @@ +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; + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Synchronized2.java b/src/com/winterbe/java8/samples/concurrent/Synchronized2.java new file mode 100644 index 00000000..98b1879c --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Synchronized2.java @@ -0,0 +1,39 @@ +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; + } + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Threads1.java b/src/com/winterbe/java8/samples/concurrent/Threads1.java new file mode 100644 index 00000000..8a64f688 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Threads1.java @@ -0,0 +1,61 @@ +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!"); + } +} diff --git a/src/com/winterbe/java8/Interface1.java b/src/com/winterbe/java8/samples/lambda/Interface1.java similarity index 94% rename from src/com/winterbe/java8/Interface1.java rename to src/com/winterbe/java8/samples/lambda/Interface1.java index faed552f..6a87fc10 100644 --- a/src/com/winterbe/java8/Interface1.java +++ b/src/com/winterbe/java8/samples/lambda/Interface1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/Lambda1.java b/src/com/winterbe/java8/samples/lambda/Lambda1.java similarity index 96% rename from src/com/winterbe/java8/Lambda1.java rename to src/com/winterbe/java8/samples/lambda/Lambda1.java index 1a98ad1b..5bb5b658 100644 --- a/src/com/winterbe/java8/Lambda1.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; import java.util.Arrays; import java.util.Collections; diff --git a/src/com/winterbe/java8/Lambda2.java b/src/com/winterbe/java8/samples/lambda/Lambda2.java similarity index 96% rename from src/com/winterbe/java8/Lambda2.java rename to src/com/winterbe/java8/samples/lambda/Lambda2.java index 1dc4ef7d..71e25ec7 100644 --- a/src/com/winterbe/java8/Lambda2.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda2.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/Lambda3.java b/src/com/winterbe/java8/samples/lambda/Lambda3.java similarity index 97% rename from src/com/winterbe/java8/Lambda3.java rename to src/com/winterbe/java8/samples/lambda/Lambda3.java index 39591ebd..967f3493 100644 --- a/src/com/winterbe/java8/Lambda3.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda3.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; import java.util.Comparator; import java.util.Objects; diff --git a/src/com/winterbe/java8/Lambda4.java b/src/com/winterbe/java8/samples/lambda/Lambda4.java similarity index 95% rename from src/com/winterbe/java8/Lambda4.java rename to src/com/winterbe/java8/samples/lambda/Lambda4.java index 705a5b53..e14b4b29 100644 --- a/src/com/winterbe/java8/Lambda4.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda4.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/samples/lambda/Lambda5.java b/src/com/winterbe/java8/samples/lambda/Lambda5.java new file mode 100644 index 00000000..68a311f4 --- /dev/null +++ b/src/com/winterbe/java8/samples/lambda/Lambda5.java @@ -0,0 +1,32 @@ +package com.winterbe.java8.samples.lambda; + +import java.util.HashMap; +import java.util.function.BiConsumer; + +/** + * Created by grijesh + */ +public class Lambda5 { + + //Pre-Defined Functional Interfaces + public static void main(String... args) { + + //BiConsumer Example + BiConsumer printKeyAndValue + = (key,value) -> System.out.println(key+"-"+value); + + printKeyAndValue.accept("One",1); + printKeyAndValue.accept("Two",2); + + System.out.println("##################"); + + //Java Hash-Map foreach supports BiConsumer + HashMap dummyValues = new HashMap<>(); + dummyValues.put("One", 1); + dummyValues.put("Two", 2); + dummyValues.put("Three", 3); + + dummyValues.forEach((key,value) -> System.out.println(key+"-"+value)); + + } +} diff --git a/src/com/winterbe/java8/samples/lambda/Person.java b/src/com/winterbe/java8/samples/lambda/Person.java new file mode 100644 index 00000000..800d39fd --- /dev/null +++ b/src/com/winterbe/java8/samples/lambda/Person.java @@ -0,0 +1,16 @@ +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; + } +} \ No newline at end of file diff --git a/src/com/winterbe/java8/Annotations1.java b/src/com/winterbe/java8/samples/misc/Annotations1.java similarity index 96% rename from src/com/winterbe/java8/Annotations1.java rename to src/com/winterbe/java8/samples/misc/Annotations1.java index cc0fd7b2..ef54072d 100644 --- a/src/com/winterbe/java8/Annotations1.java +++ b/src/com/winterbe/java8/samples/misc/Annotations1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.misc; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; diff --git a/src/com/winterbe/java8/samples/misc/CheckedFunctions.java b/src/com/winterbe/java8/samples/misc/CheckedFunctions.java new file mode 100644 index 00000000..df8168a4 --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/CheckedFunctions.java @@ -0,0 +1,92 @@ +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 { + void accept(T input) throws Exception; + } + + @FunctionalInterface + public interface CheckedPredicate { + boolean test(T input) throws Exception; + } + + @FunctionalInterface + public interface CheckedFunction { + T apply(F input) throws Exception; + } + + /** + * Return a function which rethrows possible checked exceptions as runtime exception. + * + * @param function + * @param + * @param + * @return + */ + public static Function function(CheckedFunction 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 + * @return + */ + public static Predicate predicate(CheckedPredicate 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 + * @return + */ + public static Consumer consumer(CheckedConsumer consumer) { + return input -> { + try { + consumer.accept(input); + } + catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + throw new RuntimeException(e); + } + }; + } +} diff --git a/src/com/winterbe/java8/Concurrency1.java b/src/com/winterbe/java8/samples/misc/Concurrency1.java similarity index 95% rename from src/com/winterbe/java8/Concurrency1.java rename to src/com/winterbe/java8/samples/misc/Concurrency1.java index ff3a7bf3..e7874e63 100644 --- a/src/com/winterbe/java8/Concurrency1.java +++ b/src/com/winterbe/java8/samples/misc/Concurrency1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.misc; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; diff --git a/src/com/winterbe/java8/samples/misc/Files1.java b/src/com/winterbe/java8/samples/misc/Files1.java new file mode 100644 index 00000000..ece9dbea --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/Files1.java @@ -0,0 +1,104 @@ +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 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 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 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 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 lines = Files.readAllLines(Paths.get("res/nashorn1.js")); + lines.add("print('foobar');"); + Files.write(Paths.get("res", "nashorn1-modified.js"), lines); + } +} diff --git a/src/com/winterbe/java8/Maps1.java b/src/com/winterbe/java8/samples/misc/Maps1.java similarity index 97% rename from src/com/winterbe/java8/Maps1.java rename to src/com/winterbe/java8/samples/misc/Maps1.java index 161ff638..1bc7b0dc 100644 --- a/src/com/winterbe/java8/Maps1.java +++ b/src/com/winterbe/java8/samples/misc/Maps1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.misc; import java.util.HashMap; import java.util.Map; diff --git a/src/com/winterbe/java8/samples/misc/Math1.java b/src/com/winterbe/java8/samples/misc/Math1.java new file mode 100644 index 00000000..2cebea8d --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/Math1.java @@ -0,0 +1,58 @@ +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()); + } + } +} diff --git a/src/com/winterbe/java8/samples/misc/String1.java b/src/com/winterbe/java8/samples/misc/String1.java new file mode 100644 index 00000000..0ba6ad8d --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/String1.java @@ -0,0 +1,49 @@ +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); + } +} diff --git a/src/com/winterbe/java8/Nashorn1.java b/src/com/winterbe/java8/samples/nashorn/Nashorn1.java similarity index 90% rename from src/com/winterbe/java8/Nashorn1.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn1.java index 93625d54..9a0aa7c9 100644 --- a/src/com/winterbe/java8/Nashorn1.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn1.java @@ -1,4 +1,6 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; + +import com.winterbe.java8.samples.lambda.Person; import javax.script.Invocable; import javax.script.ScriptEngine; diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn10.java b/src/com/winterbe/java8/samples/nashorn/Nashorn10.java new file mode 100644 index 00000000..ed4a6d17 --- /dev/null +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn10.java @@ -0,0 +1,27 @@ +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)); + } +} diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn11.java b/src/com/winterbe/java8/samples/nashorn/Nashorn11.java new file mode 100644 index 00000000..355e92eb --- /dev/null +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn11.java @@ -0,0 +1,157 @@ +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"); + } + +} diff --git a/src/com/winterbe/java8/Nashorn2.java b/src/com/winterbe/java8/samples/nashorn/Nashorn2.java similarity index 96% rename from src/com/winterbe/java8/Nashorn2.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn2.java index 3f7dac64..fcc36f94 100644 --- a/src/com/winterbe/java8/Nashorn2.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn2.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import jdk.nashorn.api.scripting.ScriptObjectMirror; diff --git a/src/com/winterbe/java8/Nashorn3.java b/src/com/winterbe/java8/samples/nashorn/Nashorn3.java similarity index 89% rename from src/com/winterbe/java8/Nashorn3.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn3.java index 8b3bb5e8..e4430274 100644 --- a/src/com/winterbe/java8/Nashorn3.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn3.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; diff --git a/src/com/winterbe/java8/Nashorn4.java b/src/com/winterbe/java8/samples/nashorn/Nashorn4.java similarity index 90% rename from src/com/winterbe/java8/Nashorn4.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn4.java index 8c9d3ce3..41b48db4 100644 --- a/src/com/winterbe/java8/Nashorn4.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn4.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; diff --git a/src/com/winterbe/java8/Nashorn5.java b/src/com/winterbe/java8/samples/nashorn/Nashorn5.java similarity index 94% rename from src/com/winterbe/java8/Nashorn5.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn5.java index e03123d9..dc7d2645 100644 --- a/src/com/winterbe/java8/Nashorn5.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn5.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import javax.script.Invocable; import javax.script.ScriptEngine; diff --git a/src/com/winterbe/java8/Nashorn6.java b/src/com/winterbe/java8/samples/nashorn/Nashorn6.java similarity index 95% rename from src/com/winterbe/java8/Nashorn6.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn6.java index ee51677c..aa7cc658 100644 --- a/src/com/winterbe/java8/Nashorn6.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn6.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import jdk.nashorn.api.scripting.ScriptObjectMirror; diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn7.java b/src/com/winterbe/java8/samples/nashorn/Nashorn7.java new file mode 100644 index 00000000..cc615859 --- /dev/null +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn7.java @@ -0,0 +1,43 @@ +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); + } + +} diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn8.java b/src/com/winterbe/java8/samples/nashorn/Nashorn8.java new file mode 100644 index 00000000..8de1a952 --- /dev/null +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn8.java @@ -0,0 +1,23 @@ +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] <- ??????? + } + +} diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn9.java b/src/com/winterbe/java8/samples/nashorn/Nashorn9.java new file mode 100644 index 00000000..73dd957b --- /dev/null +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn9.java @@ -0,0 +1,31 @@ +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)); + } +} diff --git a/src/com/winterbe/java8/Product.java b/src/com/winterbe/java8/samples/nashorn/Product.java similarity index 94% rename from src/com/winterbe/java8/Product.java rename to src/com/winterbe/java8/samples/nashorn/Product.java index 19b540dc..26f85fa4 100644 --- a/src/com/winterbe/java8/Product.java +++ b/src/com/winterbe/java8/samples/nashorn/Product.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/SuperRunner.java b/src/com/winterbe/java8/samples/nashorn/SuperRunner.java similarity index 79% rename from src/com/winterbe/java8/SuperRunner.java rename to src/com/winterbe/java8/samples/nashorn/SuperRunner.java index 03f7d31c..7c726e3e 100644 --- a/src/com/winterbe/java8/SuperRunner.java +++ b/src/com/winterbe/java8/samples/nashorn/SuperRunner.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/Optional1.java b/src/com/winterbe/java8/samples/stream/Optional1.java similarity index 90% rename from src/com/winterbe/java8/Optional1.java rename to src/com/winterbe/java8/samples/stream/Optional1.java index bc00b472..efd779e2 100644 --- a/src/com/winterbe/java8/Optional1.java +++ b/src/com/winterbe/java8/samples/stream/Optional1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Optional; diff --git a/src/com/winterbe/java8/samples/stream/Optional2.java b/src/com/winterbe/java8/samples/stream/Optional2.java new file mode 100644 index 00000000..920c82be --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Optional2.java @@ -0,0 +1,76 @@ +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 Optional resolve(Supplier 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); + } +} diff --git a/src/com/winterbe/java8/Streams1.java b/src/com/winterbe/java8/samples/stream/Streams1.java similarity index 98% rename from src/com/winterbe/java8/Streams1.java rename to src/com/winterbe/java8/samples/stream/Streams1.java index c482e9e3..8f438da4 100644 --- a/src/com/winterbe/java8/Streams1.java +++ b/src/com/winterbe/java8/samples/stream/Streams1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.ArrayList; import java.util.List; diff --git a/src/com/winterbe/java8/samples/stream/Streams10.java b/src/com/winterbe/java8/samples/stream/Streams10.java new file mode 100644 index 00000000..22483248 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams10.java @@ -0,0 +1,182 @@ +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 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 persons) { + List filtered = + persons + .stream() + .filter(p -> p.name.startsWith("P")) + .collect(Collectors.toList()); + + System.out.println(filtered); // [Peter, Pamela] + } + + private static void test2(List persons) { + Map> 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 persons) { + Double averageAge = persons + .stream() + .collect(Collectors.averagingInt(p -> p.age)); + + System.out.println(averageAge); // 19.0 + } + + private static void test4(List 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 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 persons) { + Map 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 persons) { + Collector 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 persons) { + Collector 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 persons) { + Collector 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 + } +} diff --git a/src/com/winterbe/java8/samples/stream/Streams11.java b/src/com/winterbe/java8/samples/stream/Streams11.java new file mode 100644 index 00000000..8ded3978 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams11.java @@ -0,0 +1,119 @@ +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 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 persons) { + persons + .stream() + .reduce((p1, p2) -> p1.age > p2.age ? p1 : p2) + .ifPresent(System.out::println); // Pamela + } + + private static void test2(List 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 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 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 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 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); + } +} diff --git a/src/com/winterbe/java8/samples/stream/Streams12.java b/src/com/winterbe/java8/samples/stream/Streams12.java new file mode 100644 index 00000000..1e59d3a2 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams12.java @@ -0,0 +1,88 @@ +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 strings = Arrays.asList("a1", "a2", "b1", "c2", "c1"); + +// test1(); +// test2(strings); + test3(strings); +// test4(); + } + + private static void test4() { + List 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 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 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()); + } +} diff --git a/src/com/winterbe/java8/samples/stream/Streams13.java b/src/com/winterbe/java8/samples/stream/Streams13.java new file mode 100644 index 00000000..50e6f7da --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams13.java @@ -0,0 +1,26 @@ +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)); + } +} diff --git a/src/com/winterbe/java8/Streams2.java b/src/com/winterbe/java8/samples/stream/Streams2.java similarity index 94% rename from src/com/winterbe/java8/Streams2.java rename to src/com/winterbe/java8/samples/stream/Streams2.java index 35258647..2569f500 100644 --- a/src/com/winterbe/java8/Streams2.java +++ b/src/com/winterbe/java8/samples/stream/Streams2.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.ArrayList; import java.util.List; diff --git a/src/com/winterbe/java8/Streams3.java b/src/com/winterbe/java8/samples/stream/Streams3.java similarity index 97% rename from src/com/winterbe/java8/Streams3.java rename to src/com/winterbe/java8/samples/stream/Streams3.java index 2510a1e0..694f6ddc 100644 --- a/src/com/winterbe/java8/Streams3.java +++ b/src/com/winterbe/java8/samples/stream/Streams3.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.ArrayList; import java.util.List; diff --git a/src/com/winterbe/java8/Streams4.java b/src/com/winterbe/java8/samples/stream/Streams4.java similarity index 95% rename from src/com/winterbe/java8/Streams4.java rename to src/com/winterbe/java8/samples/stream/Streams4.java index 0e884b79..78bf6f58 100644 --- a/src/com/winterbe/java8/Streams4.java +++ b/src/com/winterbe/java8/samples/stream/Streams4.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.OptionalInt; import java.util.stream.IntStream; diff --git a/src/com/winterbe/java8/samples/stream/Streams5.java b/src/com/winterbe/java8/samples/stream/Streams5.java new file mode 100644 index 00000000..560becf9 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams5.java @@ -0,0 +1,138 @@ +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 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 stringCollection) { + Supplier> 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 stringCollection) { + Stream stream = stringCollection + .stream() + .filter(s -> s.startsWith("a")); + + stream.anyMatch(s -> true); + stream.noneMatch(s -> true); + } + + // short-circuit + private static void test6(List 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 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 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 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 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 stringCollection) { + stringCollection + .stream() + .filter(s -> { + System.out.println("filter: " + s); + return true; + }) + .forEach(s -> System.out.println("forEach: " + s)); + } + +} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/stream/Streams6.java b/src/com/winterbe/java8/samples/stream/Streams6.java new file mode 100644 index 00000000..1e784dd8 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams6.java @@ -0,0 +1,57 @@ +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); + } +} diff --git a/src/com/winterbe/java8/samples/stream/Streams7.java b/src/com/winterbe/java8/samples/stream/Streams7.java new file mode 100644 index 00000000..e898d887 --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams7.java @@ -0,0 +1,61 @@ +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 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 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)); + } + +} \ No newline at end of file diff --git a/src/com/winterbe/java8/samples/stream/Streams8.java b/src/com/winterbe/java8/samples/stream/Streams8.java new file mode 100644 index 00000000..6687595a --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams8.java @@ -0,0 +1,39 @@ +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); + + } +} diff --git a/src/com/winterbe/java8/samples/stream/Streams9.java b/src/com/winterbe/java8/samples/stream/Streams9.java new file mode 100644 index 00000000..27757a2b --- /dev/null +++ b/src/com/winterbe/java8/samples/stream/Streams9.java @@ -0,0 +1,21 @@ +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 + } +} diff --git a/src/com/winterbe/java8/LocalDate1.java b/src/com/winterbe/java8/samples/time/LocalDate1.java similarity index 96% rename from src/com/winterbe/java8/LocalDate1.java rename to src/com/winterbe/java8/samples/time/LocalDate1.java index df19d44f..9deed2a7 100644 --- a/src/com/winterbe/java8/LocalDate1.java +++ b/src/com/winterbe/java8/samples/time/LocalDate1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.time; import java.time.DayOfWeek; import java.time.LocalDate; diff --git a/src/com/winterbe/java8/LocalDateTime1.java b/src/com/winterbe/java8/samples/time/LocalDateTime1.java similarity index 97% rename from src/com/winterbe/java8/LocalDateTime1.java rename to src/com/winterbe/java8/samples/time/LocalDateTime1.java index 8371afe0..78134f5d 100644 --- a/src/com/winterbe/java8/LocalDateTime1.java +++ b/src/com/winterbe/java8/samples/time/LocalDateTime1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.time; import java.time.DayOfWeek; import java.time.Instant; diff --git a/src/com/winterbe/java8/LocalTime1.java b/src/com/winterbe/java8/samples/time/LocalTime1.java similarity index 97% rename from src/com/winterbe/java8/LocalTime1.java rename to src/com/winterbe/java8/samples/time/LocalTime1.java index d3797a5a..763a81ff 100644 --- a/src/com/winterbe/java8/LocalTime1.java +++ b/src/com/winterbe/java8/samples/time/LocalTime1.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.time; import java.time.Clock; import java.time.Instant;