From a42a7d4d37b69e44c4507eaef40707363434ab77 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 4 Mar 2015 13:56:08 +0100 Subject: [PATCH 01/87] Add perf test to compare 8u31 vs 8u40 --- res/nashorn9.js | 9 ++++++++ src/com/winterbe/java8/Nashorn9.java | 31 ++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 res/nashorn9.js create mode 100644 src/com/winterbe/java8/Nashorn9.java 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/java8/Nashorn9.java b/src/com/winterbe/java8/Nashorn9.java new file mode 100644 index 00000000..cc898814 --- /dev/null +++ b/src/com/winterbe/java8/Nashorn9.java @@ -0,0 +1,31 @@ +package com.winterbe.java8; + +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)); + } +} From 215aed960989cb08ac53a9d9f5c51abb949dcb87 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Mon, 9 Mar 2015 16:01:14 +0100 Subject: [PATCH 02/87] Another perf test to compare 8u31 vs 8u40 --- res/nashorn10.js | 29 +++++++++++++++++++++++++++ src/com/winterbe/java8/Nashorn10.java | 27 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 res/nashorn10.js create mode 100644 src/com/winterbe/java8/Nashorn10.java 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/src/com/winterbe/java8/Nashorn10.java b/src/com/winterbe/java8/Nashorn10.java new file mode 100644 index 00000000..d1b9f845 --- /dev/null +++ b/src/com/winterbe/java8/Nashorn10.java @@ -0,0 +1,27 @@ +package com.winterbe.java8; + +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)); + } +} From e7d913356545afbce7963e7d314a826738d89d43 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 13 Mar 2015 17:24:49 +0100 Subject: [PATCH 03/87] Simplified elvis-like operator --- src/com/winterbe/java8/Take.java | 54 ++++++++++++++++++++++++++++ src/com/winterbe/java8/TakeTest.java | 46 ++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 src/com/winterbe/java8/Take.java create mode 100644 src/com/winterbe/java8/TakeTest.java diff --git a/src/com/winterbe/java8/Take.java b/src/com/winterbe/java8/Take.java new file mode 100644 index 00000000..f13e930c --- /dev/null +++ b/src/com/winterbe/java8/Take.java @@ -0,0 +1,54 @@ +package com.winterbe.java8; + +import java.util.Optional; +import java.util.function.Function; + +/** + * Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax. + * + * @see Optional2 + * @author Benjamin Winterberg + */ +public class Take { + + private static final Take EMPTY = new Take<>(null); + + private T value; + + private Take(T value) { + this.value = value; + } + + public static Take of(T something) { + return new Take<>(something); + } + + public Take take(Function mapper) { + if (!isPresent()) { + return empty(); + } + S result = mapper.apply(value); + return new Take<>(result); + } + + public Optional get() { + return Optional.ofNullable(value); + } + + public T orElse(T fallback) { + if (isPresent()) { + return value; + } + return fallback; + } + + public boolean isPresent() { + return value != null; + } + + @SuppressWarnings("unchecked") + private static Take empty() { + return (Take) EMPTY; + } + +} diff --git a/src/com/winterbe/java8/TakeTest.java b/src/com/winterbe/java8/TakeTest.java new file mode 100644 index 00000000..da97eb90 --- /dev/null +++ b/src/com/winterbe/java8/TakeTest.java @@ -0,0 +1,46 @@ +package com.winterbe.java8; + +import java.util.Optional; + +/** + * @author Benjamin Winterberg + */ +public class TakeTest { + + static class Outer { + Nested nested = new Nested(); + + Nested getNested() { + return nested; + } + } + + static class Nested { + Inner inner = new Inner(); + + Inner getInner() { + return inner; + } + } + + static class Inner { + String foo = "foo"; + + String getFoo() { + return foo; + } + } + + public static void main(String[] args) { + Outer something = new Outer(); + + Optional optional = Take.of(something) + .take(Outer::getNested) + .take(Nested::getInner) + .take(Inner::getFoo) + .get(); + + System.out.println(optional.get()); + } + +} From 76ff6b67a83a6985adb3f6c02a0539b43c053e6c Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 14 Mar 2015 07:55:06 +0100 Subject: [PATCH 04/87] More null safe operations --- src/com/winterbe/java8/Take.java | 15 +++++++++++++-- src/com/winterbe/java8/TakeTest.java | 16 +++++++++++++++- 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/com/winterbe/java8/Take.java b/src/com/winterbe/java8/Take.java index f13e930c..0e7b5358 100644 --- a/src/com/winterbe/java8/Take.java +++ b/src/com/winterbe/java8/Take.java @@ -2,6 +2,7 @@ import java.util.Optional; import java.util.function.Function; +import java.util.function.Supplier; /** * Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax. @@ -19,15 +20,25 @@ private Take(T value) { this.value = value; } + public static Optional of(Supplier resolver) { + try { + T result = resolver.get(); + return Optional.ofNullable(result); + } + catch (NullPointerException e) { + return Optional.empty(); + } + } + public static Take of(T something) { return new Take<>(something); } - public Take take(Function mapper) { + public Take take(Function resolver) { if (!isPresent()) { return empty(); } - S result = mapper.apply(value); + S result = resolver.apply(value); return new Take<>(result); } diff --git a/src/com/winterbe/java8/TakeTest.java b/src/com/winterbe/java8/TakeTest.java index da97eb90..c4567b52 100644 --- a/src/com/winterbe/java8/TakeTest.java +++ b/src/com/winterbe/java8/TakeTest.java @@ -40,7 +40,21 @@ public static void main(String[] args) { .take(Inner::getFoo) .get(); - System.out.println(optional.get()); + System.out.println(optional.isPresent()); + + something.getNested().inner = null; + Optional optional2 = Take.of(() -> + something.getNested().getInner().getFoo()); + System.out.println(optional2.isPresent()); + + + String x = null; + String y = "boo"; + String z = Take.of(x).orElse(y); + + System.out.println(z); + + } } From e2b0126f545e5ca94a38ee17b9cb055f4ebf96b1 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 14 Mar 2015 12:36:29 +0100 Subject: [PATCH 05/87] Rename to Some --- .../winterbe/java8/{Take.java => Some.java} | 26 ++++++++----------- .../java8/{TakeTest.java => SomeTest.java} | 18 +++++++------ 2 files changed, 21 insertions(+), 23 deletions(-) rename src/com/winterbe/java8/{Take.java => Some.java} (65%) rename src/com/winterbe/java8/{TakeTest.java => SomeTest.java} (71%) diff --git a/src/com/winterbe/java8/Take.java b/src/com/winterbe/java8/Some.java similarity index 65% rename from src/com/winterbe/java8/Take.java rename to src/com/winterbe/java8/Some.java index 0e7b5358..2b6209d0 100644 --- a/src/com/winterbe/java8/Take.java +++ b/src/com/winterbe/java8/Some.java @@ -10,13 +10,13 @@ * @see Optional2 * @author Benjamin Winterberg */ -public class Take { +public class Some { - private static final Take EMPTY = new Take<>(null); + private static final Some EMPTY = new Some<>(null); private T value; - private Take(T value) { + private Some(T value) { this.value = value; } @@ -30,16 +30,16 @@ public static Optional of(Supplier resolver) { } } - public static Take of(T something) { - return new Take<>(something); + public static Some of(T something) { + return new Some<>(something); } - public Take take(Function resolver) { - if (!isPresent()) { + public Some get(Function resolver) { + if (value == null) { return empty(); } S result = resolver.apply(value); - return new Take<>(result); + return new Some<>(result); } public Optional get() { @@ -47,19 +47,15 @@ public Optional get() { } public T orElse(T fallback) { - if (isPresent()) { + if (value != null) { return value; } return fallback; } - public boolean isPresent() { - return value != null; - } - @SuppressWarnings("unchecked") - private static Take empty() { - return (Take) EMPTY; + private static Some empty() { + return (Some) EMPTY; } } diff --git a/src/com/winterbe/java8/TakeTest.java b/src/com/winterbe/java8/SomeTest.java similarity index 71% rename from src/com/winterbe/java8/TakeTest.java rename to src/com/winterbe/java8/SomeTest.java index c4567b52..7e8a05a8 100644 --- a/src/com/winterbe/java8/TakeTest.java +++ b/src/com/winterbe/java8/SomeTest.java @@ -5,7 +5,7 @@ /** * @author Benjamin Winterberg */ -public class TakeTest { +public class SomeTest { static class Outer { Nested nested = new Nested(); @@ -34,23 +34,25 @@ String getFoo() { public static void main(String[] args) { Outer something = new Outer(); - Optional optional = Take.of(something) - .take(Outer::getNested) - .take(Nested::getInner) - .take(Inner::getFoo) + Optional optional = Some.of(something) + .get(Outer::getNested) + .get(Nested::getInner) + .get(Inner::getFoo) .get(); System.out.println(optional.isPresent()); something.getNested().inner = null; - Optional optional2 = Take.of(() -> + + optional = Some.of(() -> something.getNested().getInner().getFoo()); - System.out.println(optional2.isPresent()); + + System.out.println(optional.isPresent()); String x = null; String y = "boo"; - String z = Take.of(x).orElse(y); + String z = Some.of(x).orElse(y); System.out.println(z); From bbf7c93b38eb5a4e903713d5f9052872880cb4fd Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:15:48 +0100 Subject: [PATCH 06/87] Some is obsolete, can be replaced with Optional.map (see Optional2) --- src/com/winterbe/java8/Optional2.java | 57 +++++++++++++++++++++--- src/com/winterbe/java8/Some.java | 61 -------------------------- src/com/winterbe/java8/SomeTest.java | 62 --------------------------- 3 files changed, 50 insertions(+), 130 deletions(-) delete mode 100644 src/com/winterbe/java8/Some.java delete mode 100644 src/com/winterbe/java8/SomeTest.java diff --git a/src/com/winterbe/java8/Optional2.java b/src/com/winterbe/java8/Optional2.java index f2e72977..76af9a0f 100644 --- a/src/com/winterbe/java8/Optional2.java +++ b/src/com/winterbe/java8/Optional2.java @@ -1,33 +1,76 @@ package com.winterbe.java8; 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; + Nested nested = new Nested(); + + public Nested getNested() { + return nested; + } } static class Nested { - Inner inner; + Inner inner = new Inner(); + + public Inner getInner() { + return inner; + } } static class Inner { - String foo; + 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); + .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/Some.java b/src/com/winterbe/java8/Some.java deleted file mode 100644 index 2b6209d0..00000000 --- a/src/com/winterbe/java8/Some.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.winterbe.java8; - -import java.util.Optional; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax. - * - * @see Optional2 - * @author Benjamin Winterberg - */ -public class Some { - - private static final Some EMPTY = new Some<>(null); - - private T value; - - private Some(T value) { - this.value = value; - } - - public static Optional of(Supplier resolver) { - try { - T result = resolver.get(); - return Optional.ofNullable(result); - } - catch (NullPointerException e) { - return Optional.empty(); - } - } - - public static Some of(T something) { - return new Some<>(something); - } - - public Some get(Function resolver) { - if (value == null) { - return empty(); - } - S result = resolver.apply(value); - return new Some<>(result); - } - - public Optional get() { - return Optional.ofNullable(value); - } - - public T orElse(T fallback) { - if (value != null) { - return value; - } - return fallback; - } - - @SuppressWarnings("unchecked") - private static Some empty() { - return (Some) EMPTY; - } - -} diff --git a/src/com/winterbe/java8/SomeTest.java b/src/com/winterbe/java8/SomeTest.java deleted file mode 100644 index 7e8a05a8..00000000 --- a/src/com/winterbe/java8/SomeTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.winterbe.java8; - -import java.util.Optional; - -/** - * @author Benjamin Winterberg - */ -public class SomeTest { - - static class Outer { - Nested nested = new Nested(); - - Nested getNested() { - return nested; - } - } - - static class Nested { - Inner inner = new Inner(); - - Inner getInner() { - return inner; - } - } - - static class Inner { - String foo = "foo"; - - String getFoo() { - return foo; - } - } - - public static void main(String[] args) { - Outer something = new Outer(); - - Optional optional = Some.of(something) - .get(Outer::getNested) - .get(Nested::getInner) - .get(Inner::getFoo) - .get(); - - System.out.println(optional.isPresent()); - - something.getNested().inner = null; - - optional = Some.of(() -> - something.getNested().getInner().getFoo()); - - System.out.println(optional.isPresent()); - - - String x = null; - String y = "boo"; - String z = Some.of(x).orElse(y); - - System.out.println(z); - - - } - -} From 0578acfb7fd525d7cd7b6cbb0fbf36379f61c88d Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:22:50 +0100 Subject: [PATCH 07/87] Inroduce sub packages --- res/nashorn2.js | 2 +- res/nashorn4.js | 2 +- res/nashorn6.js | 2 +- src/com/winterbe/java8/Person.java | 16 ---------------- .../java8/{ => samples/lambda}/Interface1.java | 2 +- .../java8/{ => samples/lambda}/Lambda1.java | 2 +- .../java8/{ => samples/lambda}/Lambda2.java | 4 +++- .../java8/{ => samples/lambda}/Lambda3.java | 4 +++- .../java8/{ => samples/lambda}/Lambda4.java | 2 +- .../java8/{ => samples/misc}/Annotations1.java | 2 +- .../java8/{ => samples/misc}/Concurrency1.java | 2 +- .../winterbe/java8/{ => samples/misc}/Maps1.java | 2 +- src/com/winterbe/java8/samples/misc/Person.java | 16 ++++++++++++++++ .../java8/{ => samples/nashorn}/Nashorn1.java | 4 +++- .../java8/{ => samples/nashorn}/Nashorn10.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn2.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn3.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn4.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn5.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn6.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn7.java | 2 +- .../java8/{ => samples/nashorn}/Nashorn8.java | 3 ++- .../java8/{ => samples/nashorn}/Nashorn9.java | 2 +- .../java8/{ => samples/nashorn}/Product.java | 2 +- .../java8/{ => samples/nashorn}/SuperRunner.java | 2 +- .../java8/{ => samples/stream}/Optional1.java | 2 +- .../java8/{ => samples/stream}/Optional2.java | 2 +- .../java8/{ => samples/stream}/Streams1.java | 2 +- .../java8/{ => samples/stream}/Streams10.java | 2 +- .../java8/{ => samples/stream}/Streams11.java | 2 +- .../java8/{ => samples/stream}/Streams12.java | 2 +- .../java8/{ => samples/stream}/Streams13.java | 2 +- .../java8/{ => samples/stream}/Streams2.java | 2 +- .../java8/{ => samples/stream}/Streams3.java | 2 +- .../java8/{ => samples/stream}/Streams4.java | 2 +- .../java8/{ => samples/stream}/Streams5.java | 2 +- .../java8/{ => samples/stream}/Streams6.java | 2 +- .../java8/{ => samples/stream}/Streams7.java | 2 +- .../java8/{ => samples/stream}/Streams8.java | 2 +- .../java8/{ => samples/stream}/Streams9.java | 2 +- .../java8/{ => samples/time}/LocalDate1.java | 2 +- .../java8/{ => samples/time}/LocalDateTime1.java | 2 +- .../java8/{ => samples/time}/LocalTime1.java | 2 +- 43 files changed, 64 insertions(+), 57 deletions(-) delete mode 100644 src/com/winterbe/java8/Person.java rename src/com/winterbe/java8/{ => samples/lambda}/Interface1.java (94%) rename src/com/winterbe/java8/{ => samples/lambda}/Lambda1.java (96%) rename src/com/winterbe/java8/{ => samples/lambda}/Lambda2.java (93%) rename src/com/winterbe/java8/{ => samples/lambda}/Lambda3.java (95%) rename src/com/winterbe/java8/{ => samples/lambda}/Lambda4.java (95%) rename src/com/winterbe/java8/{ => samples/misc}/Annotations1.java (96%) rename src/com/winterbe/java8/{ => samples/misc}/Concurrency1.java (95%) rename src/com/winterbe/java8/{ => samples/misc}/Maps1.java (97%) create mode 100644 src/com/winterbe/java8/samples/misc/Person.java rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn1.java (90%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn10.java (94%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn2.java (96%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn3.java (89%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn4.java (90%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn5.java (94%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn6.java (95%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn7.java (96%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn8.java (90%) rename src/com/winterbe/java8/{ => samples/nashorn}/Nashorn9.java (95%) rename src/com/winterbe/java8/{ => samples/nashorn}/Product.java (94%) rename src/com/winterbe/java8/{ => samples/nashorn}/SuperRunner.java (79%) rename src/com/winterbe/java8/{ => samples/stream}/Optional1.java (90%) rename src/com/winterbe/java8/{ => samples/stream}/Optional2.java (97%) rename src/com/winterbe/java8/{ => samples/stream}/Streams1.java (98%) rename src/com/winterbe/java8/{ => samples/stream}/Streams10.java (99%) rename src/com/winterbe/java8/{ => samples/stream}/Streams11.java (98%) rename src/com/winterbe/java8/{ => samples/stream}/Streams12.java (98%) rename src/com/winterbe/java8/{ => samples/stream}/Streams13.java (93%) rename src/com/winterbe/java8/{ => samples/stream}/Streams2.java (94%) rename src/com/winterbe/java8/{ => samples/stream}/Streams3.java (97%) rename src/com/winterbe/java8/{ => samples/stream}/Streams4.java (95%) rename src/com/winterbe/java8/{ => samples/stream}/Streams5.java (98%) rename src/com/winterbe/java8/{ => samples/stream}/Streams6.java (98%) rename src/com/winterbe/java8/{ => samples/stream}/Streams7.java (96%) rename src/com/winterbe/java8/{ => samples/stream}/Streams8.java (95%) rename src/com/winterbe/java8/{ => samples/stream}/Streams9.java (90%) rename src/com/winterbe/java8/{ => samples/time}/LocalDate1.java (96%) rename src/com/winterbe/java8/{ => samples/time}/LocalDateTime1.java (97%) rename src/com/winterbe/java8/{ => samples/time}/LocalTime1.java (97%) 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/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/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 93% rename from src/com/winterbe/java8/Lambda2.java rename to src/com/winterbe/java8/samples/lambda/Lambda2.java index 1dc4ef7d..d1ced9ca 100644 --- a/src/com/winterbe/java8/Lambda2.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda2.java @@ -1,4 +1,6 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; + +import com.winterbe.java8.samples.misc.Person; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/Lambda3.java b/src/com/winterbe/java8/samples/lambda/Lambda3.java similarity index 95% rename from src/com/winterbe/java8/Lambda3.java rename to src/com/winterbe/java8/samples/lambda/Lambda3.java index 39591ebd..badd1fbc 100644 --- a/src/com/winterbe/java8/Lambda3.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda3.java @@ -1,4 +1,6 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.lambda; + +import com.winterbe.java8.samples.misc.Person; 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/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/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/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/Person.java b/src/com/winterbe/java8/samples/misc/Person.java new file mode 100644 index 00000000..439e978d --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/Person.java @@ -0,0 +1,16 @@ +package com.winterbe.java8.samples.misc; + +/** +* @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/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..254cf2f7 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.misc.Person; import javax.script.Invocable; import javax.script.ScriptEngine; diff --git a/src/com/winterbe/java8/Nashorn10.java b/src/com/winterbe/java8/samples/nashorn/Nashorn10.java similarity index 94% rename from src/com/winterbe/java8/Nashorn10.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn10.java index d1b9f845..ed4a6d17 100644 --- a/src/com/winterbe/java8/Nashorn10.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn10.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import jdk.nashorn.api.scripting.NashornScriptEngine; 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/Nashorn7.java b/src/com/winterbe/java8/samples/nashorn/Nashorn7.java similarity index 96% rename from src/com/winterbe/java8/Nashorn7.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn7.java index c753dbc6..cc615859 100644 --- a/src/com/winterbe/java8/Nashorn7.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn7.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/Nashorn8.java b/src/com/winterbe/java8/samples/nashorn/Nashorn8.java similarity index 90% rename from src/com/winterbe/java8/Nashorn8.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn8.java index eff92aae..9edb8817 100644 --- a/src/com/winterbe/java8/Nashorn8.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn8.java @@ -1,5 +1,6 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; +import com.winterbe.java8.samples.misc.Person; import jdk.nashorn.api.scripting.NashornScriptEngine; import javax.script.ScriptEngineManager; diff --git a/src/com/winterbe/java8/Nashorn9.java b/src/com/winterbe/java8/samples/nashorn/Nashorn9.java similarity index 95% rename from src/com/winterbe/java8/Nashorn9.java rename to src/com/winterbe/java8/samples/nashorn/Nashorn9.java index cc898814..73dd957b 100644 --- a/src/com/winterbe/java8/Nashorn9.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn9.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.nashorn; import jdk.nashorn.api.scripting.NashornScriptEngine; 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/Optional2.java b/src/com/winterbe/java8/samples/stream/Optional2.java similarity index 97% rename from src/com/winterbe/java8/Optional2.java rename to src/com/winterbe/java8/samples/stream/Optional2.java index 76af9a0f..920c82be 100644 --- a/src/com/winterbe/java8/Optional2.java +++ b/src/com/winterbe/java8/samples/stream/Optional2.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Optional; import java.util.function.Supplier; 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/Streams10.java b/src/com/winterbe/java8/samples/stream/Streams10.java similarity index 99% rename from src/com/winterbe/java8/Streams10.java rename to src/com/winterbe/java8/samples/stream/Streams10.java index 89e546af..22483248 100644 --- a/src/com/winterbe/java8/Streams10.java +++ b/src/com/winterbe/java8/samples/stream/Streams10.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Arrays; import java.util.IntSummaryStatistics; diff --git a/src/com/winterbe/java8/Streams11.java b/src/com/winterbe/java8/samples/stream/Streams11.java similarity index 98% rename from src/com/winterbe/java8/Streams11.java rename to src/com/winterbe/java8/samples/stream/Streams11.java index e7ab596b..8ded3978 100644 --- a/src/com/winterbe/java8/Streams11.java +++ b/src/com/winterbe/java8/samples/stream/Streams11.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Arrays; import java.util.List; diff --git a/src/com/winterbe/java8/Streams12.java b/src/com/winterbe/java8/samples/stream/Streams12.java similarity index 98% rename from src/com/winterbe/java8/Streams12.java rename to src/com/winterbe/java8/samples/stream/Streams12.java index 4020946d..1e59d3a2 100644 --- a/src/com/winterbe/java8/Streams12.java +++ b/src/com/winterbe/java8/samples/stream/Streams12.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.ArrayList; import java.util.Arrays; diff --git a/src/com/winterbe/java8/Streams13.java b/src/com/winterbe/java8/samples/stream/Streams13.java similarity index 93% rename from src/com/winterbe/java8/Streams13.java rename to src/com/winterbe/java8/samples/stream/Streams13.java index be295262..50e6f7da 100644 --- a/src/com/winterbe/java8/Streams13.java +++ b/src/com/winterbe/java8/samples/stream/Streams13.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.security.SecureRandom; import java.util.Arrays; 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/Streams5.java b/src/com/winterbe/java8/samples/stream/Streams5.java similarity index 98% rename from src/com/winterbe/java8/Streams5.java rename to src/com/winterbe/java8/samples/stream/Streams5.java index 945c8743..560becf9 100644 --- a/src/com/winterbe/java8/Streams5.java +++ b/src/com/winterbe/java8/samples/stream/Streams5.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Arrays; import java.util.List; diff --git a/src/com/winterbe/java8/Streams6.java b/src/com/winterbe/java8/samples/stream/Streams6.java similarity index 98% rename from src/com/winterbe/java8/Streams6.java rename to src/com/winterbe/java8/samples/stream/Streams6.java index b2f590fe..21801a80 100644 --- a/src/com/winterbe/java8/Streams6.java +++ b/src/com/winterbe/java8/samples/stream/Streams6.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.io.IOException; import java.math.BigDecimal; diff --git a/src/com/winterbe/java8/Streams7.java b/src/com/winterbe/java8/samples/stream/Streams7.java similarity index 96% rename from src/com/winterbe/java8/Streams7.java rename to src/com/winterbe/java8/samples/stream/Streams7.java index 4d46dcd4..e898d887 100644 --- a/src/com/winterbe/java8/Streams7.java +++ b/src/com/winterbe/java8/samples/stream/Streams7.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/Streams8.java b/src/com/winterbe/java8/samples/stream/Streams8.java similarity index 95% rename from src/com/winterbe/java8/Streams8.java rename to src/com/winterbe/java8/samples/stream/Streams8.java index 4a1ad25a..6687595a 100644 --- a/src/com/winterbe/java8/Streams8.java +++ b/src/com/winterbe/java8/samples/stream/Streams8.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Arrays; import java.util.stream.IntStream; diff --git a/src/com/winterbe/java8/Streams9.java b/src/com/winterbe/java8/samples/stream/Streams9.java similarity index 90% rename from src/com/winterbe/java8/Streams9.java rename to src/com/winterbe/java8/samples/stream/Streams9.java index 987a9435..27757a2b 100644 --- a/src/com/winterbe/java8/Streams9.java +++ b/src/com/winterbe/java8/samples/stream/Streams9.java @@ -1,4 +1,4 @@ -package com.winterbe.java8; +package com.winterbe.java8.samples.stream; import java.util.Arrays; 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; From be4a4c8ce0a51352b4c5d3033f97b2f06c3b7dbd Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:31:06 +0100 Subject: [PATCH 08/87] Update README.md --- README.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 87fd0c6d..b8e84d73 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,14 @@ -Java 8 Tutorial +Java 8 Tutorial Examples ============== -This repository contains all code samples from the Java 8 Tutorials of my blog: +This repository contains all code samples from all Java 8 related posts of my blog: -- http://winterbe.com/posts/2014/03/16/java-8-tutorial/ -- http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ -- http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/ -- http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/ +- [Java 8 Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) +- [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) +- [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/) +- [Avoid Null Checks in Java 8](http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/) +- [Fixing Java 8 Stream Gotchas with IntelliJ IDEA](http://winterbe.com/posts/2015/03/05/fixing-java-8-stream-gotchas-with-intellij-idea/) +- [Using Backbone.js with Java 8 Nashorn](http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/) I'm adding new samples from time to time, but feel free to fork and try it yourself. From b21213fb0530c52c6d9c04edb98560442df1ab3f Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:32:00 +0100 Subject: [PATCH 09/87] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b8e84d73..63e3187d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Java 8 Tutorial Examples ============== -This repository contains all code samples from all Java 8 related posts of my blog: +This repository contains all code samples from all Java 8 related posts of my [blog](http://winterbe.com): - [Java 8 Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) From 8927863c3c2d7e08c64565ec827cd2225e856f3f Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:32:19 +0100 Subject: [PATCH 10/87] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 63e3187d..3156fd74 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ Java 8 Tutorial Examples ============== -This repository contains all code samples from all Java 8 related posts of my [blog](http://winterbe.com): +This repository contains all code samples from the Java 8 related posts of my [blog](http://winterbe.com): - [Java 8 Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) From f9271f14f543bc89ecf9b939aba110073ea8d75d Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:33:15 +0100 Subject: [PATCH 11/87] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3156fd74..beb00322 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This repository contains all code samples from the Java 8 related posts of my [b - [Fixing Java 8 Stream Gotchas with IntelliJ IDEA](http://winterbe.com/posts/2015/03/05/fixing-java-8-stream-gotchas-with-intellij-idea/) - [Using Backbone.js with Java 8 Nashorn](http://winterbe.com/posts/2014/04/07/using-backbonejs-with-nashorn/) -I'm adding new samples from time to time, but feel free to fork and try it yourself. +I'm adding new samples from time to time. Contribute From 83ded3744b1a399dcf7d86260aca32f8bdb03bd4 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 07:56:23 +0100 Subject: [PATCH 12/87] Strict Math sample --- .../java8/samples/misc/StrictMath1.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/com/winterbe/java8/samples/misc/StrictMath1.java diff --git a/src/com/winterbe/java8/samples/misc/StrictMath1.java b/src/com/winterbe/java8/samples/misc/StrictMath1.java new file mode 100644 index 00000000..af398bb1 --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/StrictMath1.java @@ -0,0 +1,18 @@ +package com.winterbe.java8.samples.misc; + +/** + * @author Benjamin Winterberg + */ +public class StrictMath1 { + + public static void main(String[] args) { + System.out.println(Integer.MAX_VALUE + 1); + + try { + Math.addExact(Integer.MAX_VALUE, 1); + } + catch (ArithmeticException e) { + System.out.println(e.getMessage()); + } + } +} From 34a42c5a181b1bddfc338ca407c94409fae4e416 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 17:15:30 +0100 Subject: [PATCH 13/87] StrictMath and unsigned ints --- .../winterbe/java8/samples/misc/Math1.java | 57 +++++++++++++++++++ .../java8/samples/misc/StrictMath1.java | 18 ------ 2 files changed, 57 insertions(+), 18 deletions(-) create mode 100644 src/com/winterbe/java8/samples/misc/Math1.java delete mode 100644 src/com/winterbe/java8/samples/misc/StrictMath1.java 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..c0080d4a --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/Math1.java @@ -0,0 +1,57 @@ +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 { + System.out.println(Integer.parseInt(string, 10)); + } + catch (NumberFormatException e) { + System.out.println("could not parse signed int of " + maxUnsignedInt); + } + } + + private static void testMathExact() { + System.out.println(Integer.MAX_VALUE + 1); + + try { + Math.addExact(Integer.MAX_VALUE, 1); + } + catch (ArithmeticException e) { + System.out.println(e.getMessage()); + } + + try { + Math.toIntExact(Long.MAX_VALUE); + } + catch (Exception e) { + System.out.println(e.getMessage()); + } + } +} diff --git a/src/com/winterbe/java8/samples/misc/StrictMath1.java b/src/com/winterbe/java8/samples/misc/StrictMath1.java deleted file mode 100644 index af398bb1..00000000 --- a/src/com/winterbe/java8/samples/misc/StrictMath1.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.winterbe.java8.samples.misc; - -/** - * @author Benjamin Winterberg - */ -public class StrictMath1 { - - public static void main(String[] args) { - System.out.println(Integer.MAX_VALUE + 1); - - try { - Math.addExact(Integer.MAX_VALUE, 1); - } - catch (ArithmeticException e) { - System.out.println(e.getMessage()); - } - } -} From b9ac0f3093db53573e5ef4be8464fd7a34c05d37 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 17:23:28 +0100 Subject: [PATCH 14/87] String stuff --- .../winterbe/java8/samples/misc/String1.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/com/winterbe/java8/samples/misc/String1.java 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..b278399d --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/String1.java @@ -0,0 +1,35 @@ +package com.winterbe.java8.samples.misc; + +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/** + * @author Benjamin Winterberg + */ +public class String1 { + + public static void main(String[] args) { + testJoin(); + testPatternPredicate(); + testPatternSplit(); + } + + private static void testPatternSplit() { + Pattern.compile(":") + .splitAsStream("foobar:foo:bar") + .sorted() + .forEach(System.out::println); + } + + private static void testPatternPredicate() { + Pattern pattern = Pattern.compile(".*123.*"); + Predicate predicate = pattern.asPredicate(); + System.out.println(predicate.test("a123b")); + System.out.println(predicate.test("boom")); + } + + private static void testJoin() { + String string = String.join(";", "a", "b", "c", "d"); + System.out.println(string); + } +} From 7e0da89e44caaef4b2ffd0053bbfe42c30cc8cf7 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 17 Mar 2015 17:24:01 +0100 Subject: [PATCH 15/87] Move to appropriate package --- src/com/winterbe/java8/samples/lambda/Lambda2.java | 2 -- src/com/winterbe/java8/samples/lambda/Lambda3.java | 2 -- src/com/winterbe/java8/samples/{misc => lambda}/Person.java | 2 +- src/com/winterbe/java8/samples/nashorn/Nashorn1.java | 2 +- src/com/winterbe/java8/samples/nashorn/Nashorn8.java | 2 +- 5 files changed, 3 insertions(+), 7 deletions(-) rename src/com/winterbe/java8/samples/{misc => lambda}/Person.java (86%) diff --git a/src/com/winterbe/java8/samples/lambda/Lambda2.java b/src/com/winterbe/java8/samples/lambda/Lambda2.java index d1ced9ca..71e25ec7 100644 --- a/src/com/winterbe/java8/samples/lambda/Lambda2.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda2.java @@ -1,7 +1,5 @@ package com.winterbe.java8.samples.lambda; -import com.winterbe.java8.samples.misc.Person; - /** * @author Benjamin Winterberg */ diff --git a/src/com/winterbe/java8/samples/lambda/Lambda3.java b/src/com/winterbe/java8/samples/lambda/Lambda3.java index badd1fbc..967f3493 100644 --- a/src/com/winterbe/java8/samples/lambda/Lambda3.java +++ b/src/com/winterbe/java8/samples/lambda/Lambda3.java @@ -1,7 +1,5 @@ package com.winterbe.java8.samples.lambda; -import com.winterbe.java8.samples.misc.Person; - import java.util.Comparator; import java.util.Objects; import java.util.UUID; diff --git a/src/com/winterbe/java8/samples/misc/Person.java b/src/com/winterbe/java8/samples/lambda/Person.java similarity index 86% rename from src/com/winterbe/java8/samples/misc/Person.java rename to src/com/winterbe/java8/samples/lambda/Person.java index 439e978d..800d39fd 100644 --- a/src/com/winterbe/java8/samples/misc/Person.java +++ b/src/com/winterbe/java8/samples/lambda/Person.java @@ -1,4 +1,4 @@ -package com.winterbe.java8.samples.misc; +package com.winterbe.java8.samples.lambda; /** * @author Benjamin Winterberg diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn1.java b/src/com/winterbe/java8/samples/nashorn/Nashorn1.java index 254cf2f7..9a0aa7c9 100644 --- a/src/com/winterbe/java8/samples/nashorn/Nashorn1.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn1.java @@ -1,6 +1,6 @@ package com.winterbe.java8.samples.nashorn; -import com.winterbe.java8.samples.misc.Person; +import com.winterbe.java8.samples.lambda.Person; import javax.script.Invocable; import javax.script.ScriptEngine; diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn8.java b/src/com/winterbe/java8/samples/nashorn/Nashorn8.java index 9edb8817..8de1a952 100644 --- a/src/com/winterbe/java8/samples/nashorn/Nashorn8.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn8.java @@ -1,6 +1,6 @@ package com.winterbe.java8.samples.nashorn; -import com.winterbe.java8.samples.misc.Person; +import com.winterbe.java8.samples.lambda.Person; import jdk.nashorn.api.scripting.NashornScriptEngine; import javax.script.ScriptEngineManager; From e2b2a1fe02b890bea309fd8714cc6ba268d99a9d Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 18 Mar 2015 07:07:55 +0100 Subject: [PATCH 16/87] Chars as int stream --- src/com/winterbe/java8/samples/misc/String1.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/com/winterbe/java8/samples/misc/String1.java b/src/com/winterbe/java8/samples/misc/String1.java index b278399d..56defaca 100644 --- a/src/com/winterbe/java8/samples/misc/String1.java +++ b/src/com/winterbe/java8/samples/misc/String1.java @@ -10,10 +10,19 @@ public class String1 { public static void main(String[] args) { testJoin(); + testChars(); testPatternPredicate(); testPatternSplit(); } + private static void testChars() { + String string = "foobar"; + string.chars() + .filter(c -> c > 100) + .mapToObj(c -> (char)c) + .forEach(System.out::println); + } + private static void testPatternSplit() { Pattern.compile(":") .splitAsStream("foobar:foo:bar") From fee263c24f185af1c8ffa08d4f049cca824ae6dc Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 18 Mar 2015 07:38:23 +0100 Subject: [PATCH 17/87] Files examples --- .../winterbe/java8/samples/misc/Files1.java | 76 +++++++++++++++++++ .../java8/samples/stream/Streams6.java | 50 +----------- 2 files changed, 80 insertions(+), 46 deletions(-) create mode 100644 src/com/winterbe/java8/samples/misc/Files1.java 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..042cbf5f --- /dev/null +++ b/src/com/winterbe/java8/samples/misc/Files1.java @@ -0,0 +1,76 @@ +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; + +/** + * @author Benjamin Winterberg + */ +public class Files1 { + + public static void main(String[] args) throws IOException { + testWalk(); + testFind(); + testList(); + testLines(); + testReader(); + testWriter(); + testReadWriteLines(); + } + + private static void testWriter() throws IOException { + try (BufferedWriter writer = + Files.newBufferedWriter(Paths.get("res", "output.js"))) { + writer.write("print('Hello World');"); + } + } + + private static void testReader() throws IOException { + try (BufferedReader reader = + Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) { + System.out.println(reader.readLine()); + } + } + + private static void testWalk() throws IOException { + Path start = Paths.get("/Users/benny/Documents"); + int maxDepth = 5; + long fileCount = Files + .walk(start, maxDepth) + .filter(path -> String.valueOf(path).endsWith("xls")) + .count(); + System.out.format("XLS files found: %s", fileCount); + } + + private static void testFind() throws IOException { + Path start = Paths.get("/Users/benny/Documents"); + int maxDepth = 5; + Files.find(start, maxDepth, (path, attr) -> + String.valueOf(path).endsWith("xls")) + .sorted() + .forEach(System.out::println); + } + + private static void testList() throws IOException { + Files.list(Paths.get("/usr")) + .sorted() + .forEach(System.out::println); + } + + private static void testLines() throws IOException { + Files.lines(Paths.get("res", "nashorn1.js")) + .filter(line -> line.contains("print")) + .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/samples/stream/Streams6.java b/src/com/winterbe/java8/samples/stream/Streams6.java index 21801a80..1e784dd8 100644 --- a/src/com/winterbe/java8/samples/stream/Streams6.java +++ b/src/com/winterbe/java8/samples/stream/Streams6.java @@ -2,9 +2,6 @@ import java.io.IOException; import java.math.BigDecimal; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.Stream; @@ -15,49 +12,10 @@ public class Streams6 { public static void main(String[] args) throws IOException { -// test1(); -// test2(); -// test3(); -// test4(); -// test5(); -// test6(); -// test7(); - test8(); - } - - private static void test8() throws IOException { - Path start = Paths.get("/Users/benny/Documents"); - int maxDepth = 5; - long fileCount = - Files - .walk(start, maxDepth) - .filter(path -> String.valueOf(path).endsWith("xls")) - .count(); - System.out.format("XLS files found: %s", fileCount); - } - - private static void test7() throws IOException { - Path start = Paths.get("/Users/benny/Documents"); - int maxDepth = 5; - Files - .find(start, maxDepth, (path, attr) -> - String.valueOf(path).endsWith("xls")) - .sorted() - .forEach(System.out::println); - } - - private static void test6() throws IOException { - Files - .list(Paths.get("/usr")) - .sorted() - .forEach(System.out::println); - } - - private static void test5() throws IOException { - Files - .lines(Paths.get("/foo", "bar")) - .filter(line -> line.startsWith("A")) - .forEach(System.out::println); + test1(); + test2(); + test3(); + test4(); } private static void test4() { From 0c4f633596379389fd98341e1e7137a6b5021684 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 18 Mar 2015 08:15:13 +0100 Subject: [PATCH 18/87] Files examples --- src/com/winterbe/java8/samples/misc/Files1.java | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/com/winterbe/java8/samples/misc/Files1.java b/src/com/winterbe/java8/samples/misc/Files1.java index 042cbf5f..401b37fd 100644 --- a/src/com/winterbe/java8/samples/misc/Files1.java +++ b/src/com/winterbe/java8/samples/misc/Files1.java @@ -21,6 +21,17 @@ public static void main(String[] args) throws IOException { testReader(); testWriter(); testReadWriteLines(); + testReaderLines(); + } + + private static void testReaderLines() throws IOException { + try (BufferedReader reader = + Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) { + long countPrints = reader.lines() + .filter(line -> line.contains("print")) + .count(); + System.out.println(countPrints); + } } private static void testWriter() throws IOException { From 70a38ae1d04fe22a9fde47f6cbde6325f7d9b1d2 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 19 Mar 2015 08:37:29 +0100 Subject: [PATCH 19/87] Add proper try/with statements --- .../winterbe/java8/samples/misc/Files1.java | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/src/com/winterbe/java8/samples/misc/Files1.java b/src/com/winterbe/java8/samples/misc/Files1.java index 401b37fd..8ceea8bc 100644 --- a/src/com/winterbe/java8/samples/misc/Files1.java +++ b/src/com/winterbe/java8/samples/misc/Files1.java @@ -7,6 +7,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.stream.Stream; /** * @author Benjamin Winterberg @@ -49,34 +50,37 @@ private static void testReader() throws IOException { } private static void testWalk() throws IOException { - Path start = Paths.get("/Users/benny/Documents"); + Path start = Paths.get(""); int maxDepth = 5; - long fileCount = Files - .walk(start, maxDepth) - .filter(path -> String.valueOf(path).endsWith("xls")) - .count(); - System.out.format("XLS files found: %s", fileCount); + try (Stream stream = Files.walk(start, maxDepth)) { + long fileCount = stream + .filter(path -> String.valueOf(path).endsWith(".js")) + .count(); + System.out.format("JS files found: %s", fileCount); + } } private static void testFind() throws IOException { - Path start = Paths.get("/Users/benny/Documents"); + Path start = Paths.get(""); int maxDepth = 5; - Files.find(start, maxDepth, (path, attr) -> - String.valueOf(path).endsWith("xls")) - .sorted() - .forEach(System.out::println); + try (Stream stream = Files.find(start, maxDepth, (path, attr) -> + String.valueOf(path).endsWith(".js"))) { + stream.sorted().forEach(System.out::println); + } } private static void testList() throws IOException { - Files.list(Paths.get("/usr")) - .sorted() - .forEach(System.out::println); + try (Stream stream = Files.list(Paths.get("/usr"))) { + stream.sorted().forEach(System.out::println); + } } private static void testLines() throws IOException { - Files.lines(Paths.get("res", "nashorn1.js")) - .filter(line -> line.contains("print")) - .forEach(System.out::println); + try (Stream stream = Files.lines(Paths.get("res", "nashorn1.js"))) { + stream + .filter(line -> line.contains("print")) + .forEach(System.out::println); + } } private static void testReadWriteLines() throws IOException { From 43128abc3cb15145eec8318503a84bbc7964d1c2 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 20 Mar 2015 08:53:10 +0100 Subject: [PATCH 20/87] Code samples --- .../winterbe/java8/samples/misc/Files1.java | 45 ++++++++++++------- .../winterbe/java8/samples/misc/Math1.java | 11 ++--- .../winterbe/java8/samples/misc/String1.java | 31 +++++++------ 3 files changed, 53 insertions(+), 34 deletions(-) diff --git a/src/com/winterbe/java8/samples/misc/Files1.java b/src/com/winterbe/java8/samples/misc/Files1.java index 8ceea8bc..ece9dbea 100644 --- a/src/com/winterbe/java8/samples/misc/Files1.java +++ b/src/com/winterbe/java8/samples/misc/Files1.java @@ -7,6 +7,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.stream.Collectors; import java.util.stream.Stream; /** @@ -26,9 +27,10 @@ public static void main(String[] args) throws IOException { } private static void testReaderLines() throws IOException { - try (BufferedReader reader = - Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) { - long countPrints = reader.lines() + 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); @@ -36,15 +38,15 @@ private static void testReaderLines() throws IOException { } private static void testWriter() throws IOException { - try (BufferedWriter writer = - Files.newBufferedWriter(Paths.get("res", "output.js"))) { + Path path = Paths.get("res/output.js"); + try (BufferedWriter writer = Files.newBufferedWriter(path)) { writer.write("print('Hello World');"); } } private static void testReader() throws IOException { - try (BufferedReader reader = - Files.newBufferedReader(Paths.get("res", "nashorn1.js"))) { + Path path = Paths.get("res/nashorn1.js"); + try (BufferedReader reader = Files.newBufferedReader(path)) { System.out.println(reader.readLine()); } } @@ -53,10 +55,11 @@ private static void testWalk() throws IOException { Path start = Paths.get(""); int maxDepth = 5; try (Stream stream = Files.walk(start, maxDepth)) { - long fileCount = stream - .filter(path -> String.valueOf(path).endsWith(".js")) - .count(); - System.out.format("JS files found: %s", fileCount); + String joined = stream + .map(String::valueOf) + .filter(path -> path.endsWith(".js")) + .collect(Collectors.joining("; ")); + System.out.println("walk(): " + joined); } } @@ -65,26 +68,36 @@ private static void testFind() throws IOException { int maxDepth = 5; try (Stream stream = Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".js"))) { - stream.sorted().forEach(System.out::println); + 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("/usr"))) { - stream.sorted().forEach(System.out::println); + 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"))) { + 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")); + 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/samples/misc/Math1.java b/src/com/winterbe/java8/samples/misc/Math1.java index c0080d4a..2cebea8d 100644 --- a/src/com/winterbe/java8/samples/misc/Math1.java +++ b/src/com/winterbe/java8/samples/misc/Math1.java @@ -30,28 +30,29 @@ private static void testUnsignedInt() { System.out.println(string2); try { - System.out.println(Integer.parseInt(string, 10)); + Integer.parseInt(string, 10); } catch (NumberFormatException e) { - System.out.println("could not parse signed int of " + maxUnsignedInt); + 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.out.println(e.getMessage()); + System.err.println(e.getMessage()); } try { Math.toIntExact(Long.MAX_VALUE); } - catch (Exception e) { - System.out.println(e.getMessage()); + 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 index 56defaca..0ba6ad8d 100644 --- a/src/com/winterbe/java8/samples/misc/String1.java +++ b/src/com/winterbe/java8/samples/misc/String1.java @@ -1,7 +1,8 @@ package com.winterbe.java8.samples.misc; -import java.util.function.Predicate; import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * @author Benjamin Winterberg @@ -16,29 +17,33 @@ public static void main(String[] args) { } private static void testChars() { - String string = "foobar"; - string.chars() - .filter(c -> c > 100) - .mapToObj(c -> (char)c) - .forEach(System.out::println); + 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() { - Pattern.compile(":") + String string = Pattern.compile(":") .splitAsStream("foobar:foo:bar") + .filter(s -> s.contains("bar")) .sorted() - .forEach(System.out::println); + .collect(Collectors.joining(":")); + System.out.println(string); } private static void testPatternPredicate() { - Pattern pattern = Pattern.compile(".*123.*"); - Predicate predicate = pattern.asPredicate(); - System.out.println(predicate.test("a123b")); - System.out.println(predicate.test("boom")); + 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(";", "a", "b", "c", "d"); + String string = String.join(":", "foobar", "foo", "bar"); System.out.println(string); } } From 48333293a3497405d6f1c7b7d8677e98d66f4f2e Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 20 Mar 2015 08:58:28 +0100 Subject: [PATCH 21/87] Utility for handling checked exceptions in lambdas --- .../java8/samples/misc/CheckedFunctions.java | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 src/com/winterbe/java8/samples/misc/CheckedFunctions.java 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); + } + }; + } +} From e3fa0ddde7bf895fc4babae6482c0c4258c785eb Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 25 Mar 2015 09:30:40 +0100 Subject: [PATCH 22/87] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index beb00322..f98e4245 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ This repository contains all code samples from the Java 8 related posts of my [b - [Java 8 Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) - [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/) +- [Java 8 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/) From 6cc2d1ffc50e9f597cd6bf83baf9f842d1297ead Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 26 Mar 2015 07:56:40 +0100 Subject: [PATCH 23/87] CompletableFuture example --- .../concurrent/CompletableFuture1.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/CompletableFuture1.java 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")); + + } + +} From ca2c72389649da5688b780746570a9c621b21ac1 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 26 Mar 2015 09:14:05 +0100 Subject: [PATCH 24/87] Concurrency samples --- .../java8/samples/concurrent/Threads1.java | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Threads1.java 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..2470aad1 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Threads1.java @@ -0,0 +1,58 @@ +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 = () -> System.out.println("Hello " + Thread.currentThread().getName()); + + runnable.run(); + + Thread thread = new Thread(runnable); + thread.start(); + + System.out.println("Nachos!"); + } +} From 15bf517ae667732621f86265e63badef2eb4505d Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 27 Mar 2015 07:21:18 +0100 Subject: [PATCH 25/87] Executors example --- .../java8/samples/concurrent/Executors1.java | 45 +++++++++++ .../java8/samples/concurrent/Executors2.java | 77 +++++++++++++++++++ 2 files changed, 122 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Executors1.java create mode 100644 src/com/winterbe/java8/samples/concurrent/Executors2.java 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..5425471d --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Executors1.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.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); + System.out.println("task finished: " + Thread.currentThread().getName()); + } + catch (InterruptedException e) { + System.err.println("task interrupted"); + } + }); + shutdown(executor); + } + + static void shutdown(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 { + 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..b6a4efba --- /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.newSingleThreadExecutor(); + + 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.newSingleThreadExecutor(); + + 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.newSingleThreadExecutor(); + + 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(); + } + +} From 28e578227501a63c61b8ac8ad642508191933fc6 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 27 Mar 2015 11:19:03 +0100 Subject: [PATCH 26/87] Scheduled executors --- .../java8/samples/concurrent/Executors3.java | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Executors3.java 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..8712ee31 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Executors3.java @@ -0,0 +1,97 @@ +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); + executor.scheduleWithFixedDelay(() -> { + try { + TimeUnit.SECONDS.sleep(2); + System.out.println("Scheduling: " + System.nanoTime()); + } + catch (InterruptedException e) { + System.err.println("task interrupted"); + } + }, 0, 1, TimeUnit.SECONDS); + } + + private static void test2() { + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + executor.scheduleAtFixedRate(() -> System.out.println("Scheduling: " + System.nanoTime()), 0, 1, TimeUnit.SECONDS); + } + + private static void test1() throws InterruptedException { + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + ScheduledFuture future = executor.schedule(() -> System.out.println("Scheduling: " + System.nanoTime()), 3, TimeUnit.SECONDS); + TimeUnit.MILLISECONDS.sleep(1337); + long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS); + System.out.printf("Remaining Delay: %sms\n", remainingDelay); + } + +} From 89a257129873974e4beb658115e854649b9204b2 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sun, 29 Mar 2015 09:10:14 +0200 Subject: [PATCH 27/87] Executors example --- .../java8/samples/concurrent/Executors1.java | 10 +++++--- .../java8/samples/concurrent/Executors2.java | 6 ++--- .../java8/samples/concurrent/Executors3.java | 23 ++++++++++++++----- .../java8/samples/concurrent/Threads1.java | 11 +++++---- 4 files changed, 34 insertions(+), 16 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Executors1.java b/src/com/winterbe/java8/samples/concurrent/Executors1.java index 5425471d..9762938d 100644 --- a/src/com/winterbe/java8/samples/concurrent/Executors1.java +++ b/src/com/winterbe/java8/samples/concurrent/Executors1.java @@ -19,16 +19,17 @@ private static void test1(long seconds) { executor.submit(() -> { try { TimeUnit.SECONDS.sleep(seconds); - System.out.println("task finished: " + Thread.currentThread().getName()); + String name = Thread.currentThread().getName(); + System.out.println("task finished: " + name); } catch (InterruptedException e) { System.err.println("task interrupted"); } }); - shutdown(executor); + stop(executor); } - static void shutdown(ExecutorService executor) { + static void stop(ExecutorService executor) { try { System.out.println("attempt to shutdown executor"); executor.shutdown(); @@ -38,6 +39,9 @@ static void shutdown(ExecutorService executor) { 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 index b6a4efba..33dda88e 100644 --- a/src/com/winterbe/java8/samples/concurrent/Executors2.java +++ b/src/com/winterbe/java8/samples/concurrent/Executors2.java @@ -19,7 +19,7 @@ public static void main(String[] args) throws ExecutionException, InterruptedExc } private static void test3() throws InterruptedException, ExecutionException, TimeoutException { - ExecutorService executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newFixedThreadPool(1); Future future = executor.submit(() -> { try { @@ -35,7 +35,7 @@ private static void test3() throws InterruptedException, ExecutionException, Tim } private static void test2() throws InterruptedException, ExecutionException { - ExecutorService executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newFixedThreadPool(1); Future future = executor.submit(() -> { try { @@ -52,7 +52,7 @@ private static void test2() throws InterruptedException, ExecutionException { } private static void test1() throws InterruptedException, ExecutionException { - ExecutorService executor = Executors.newSingleThreadExecutor(); + ExecutorService executor = Executors.newFixedThreadPool(1); Future future = executor.submit(() -> { try { diff --git a/src/com/winterbe/java8/samples/concurrent/Executors3.java b/src/com/winterbe/java8/samples/concurrent/Executors3.java index 8712ee31..75e60377 100644 --- a/src/com/winterbe/java8/samples/concurrent/Executors3.java +++ b/src/com/winterbe/java8/samples/concurrent/Executors3.java @@ -16,12 +16,12 @@ public class Executors3 { public static void main(String[] args) throws InterruptedException, ExecutionException { -// test1(); + test1(); // test2(); // test3(); // test4(); - test5(); +// test5(); } private static void test5() throws InterruptedException, ExecutionException { @@ -70,7 +70,8 @@ private static void test4() throws InterruptedException { private static void test3() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - executor.scheduleWithFixedDelay(() -> { + + Runnable task = () -> { try { TimeUnit.SECONDS.sleep(2); System.out.println("Scheduling: " + System.nanoTime()); @@ -78,18 +79,28 @@ private static void test3() { catch (InterruptedException e) { System.err.println("task interrupted"); } - }, 0, 1, TimeUnit.SECONDS); + }; + + executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); } private static void test2() { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); - executor.scheduleAtFixedRate(() -> System.out.println("Scheduling: " + System.nanoTime()), 0, 1, TimeUnit.SECONDS); + 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); - ScheduledFuture future = executor.schedule(() -> System.out.println("Scheduling: " + System.nanoTime()), 3, TimeUnit.SECONDS); + + 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/Threads1.java b/src/com/winterbe/java8/samples/concurrent/Threads1.java index 2470aad1..8a64f688 100644 --- a/src/com/winterbe/java8/samples/concurrent/Threads1.java +++ b/src/com/winterbe/java8/samples/concurrent/Threads1.java @@ -9,8 +9,8 @@ public class Threads1 { public static void main(String[] args) { test1(); - test2(); - test3(); +// test2(); +// test3(); } private static void test3() { @@ -46,13 +46,16 @@ private static void test2() { } private static void test1() { - Runnable runnable = () -> System.out.println("Hello " + Thread.currentThread().getName()); + Runnable runnable = () -> { + String threadName = Thread.currentThread().getName(); + System.out.println("Hello " + threadName); + }; runnable.run(); Thread thread = new Thread(runnable); thread.start(); - System.out.println("Nachos!"); + System.out.println("Done!"); } } From b81681c36756124cc74db3ee6a7e3e841d247d75 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 9 Apr 2015 07:41:55 +0200 Subject: [PATCH 28/87] Test synchronized --- .../samples/concurrent/ConcurrentUtils.java | 27 ++++++++++ .../samples/concurrent/Synchronized1.java | 54 +++++++++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java create mode 100644 src/com/winterbe/java8/samples/concurrent/Synchronized1.java 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..70788223 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java @@ -0,0 +1,27 @@ +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(5, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + System.err.println("termination interrupted"); + } + finally { + if (!executor.isTerminated()) { + System.err.println("killing non-finished tasks"); + } + executor.shutdownNow(); + } + } + +} 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..19bf9c5f --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java @@ -0,0 +1,54 @@ +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 = 1; + + public static void main(String[] args) { + testSyncIncrement(); + testNonSyncIncrement(); + } + + private static void testSyncIncrement() { + count = 1; + + 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 = 1; + + 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; + } +} From e7995a8f625c80a6534b9feb9e965b7c5ff891e2 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 9 Apr 2015 09:05:39 +0200 Subject: [PATCH 29/87] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f98e4245..aa0dd99f 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ This repository contains all code samples from the Java 8 related posts of my [b - [Java 8 Tutorial](http://winterbe.com/posts/2014/03/16/java-8-tutorial/) - [Java 8 Stream Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/) - [Java 8 Nashorn Tutorial](http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/) +- [Java 8 Concurrency Tutorial: Threads and Executors](http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/) - [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/) From e8cc2fc68ce91bf441a985b86598db9e7d4f5614 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 11 Apr 2015 08:13:28 +0200 Subject: [PATCH 30/87] Test AtomicInteger --- .../java8/samples/concurrent/Atomic1.java | 34 +++++++++++++++++++ .../samples/concurrent/Synchronized1.java | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/com/winterbe/java8/samples/concurrent/Atomic1.java 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..ad4160ae --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -0,0 +1,34 @@ +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 = 10000; + + private static AtomicInteger count = new AtomicInteger(0); + + public static void main(String[] args) { + testIncrement(); + } + + private static void testIncrement() { + count.set(0); + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(count::incrementAndGet)); + + ConcurrentUtils.stop(executor); + + System.out.format("Expected=%d; Is=%d", NUM_INCREMENTS, count.get()); + } + +} diff --git a/src/com/winterbe/java8/samples/concurrent/Synchronized1.java b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java index 19bf9c5f..06b14648 100644 --- a/src/com/winterbe/java8/samples/concurrent/Synchronized1.java +++ b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java @@ -11,7 +11,7 @@ public class Synchronized1 { private static final int NUM_INCREMENTS = 10000; - private static int count = 1; + private static int count = 0; public static void main(String[] args) { testSyncIncrement(); From e98f201d77c00aa6f8e5983dac34fb935fd902f7 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 11 Apr 2015 09:11:57 +0200 Subject: [PATCH 31/87] Atomic accumulate --- .../java8/samples/concurrent/Atomic1.java | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Atomic1.java b/src/com/winterbe/java8/samples/concurrent/Atomic1.java index ad4160ae..a23244eb 100644 --- a/src/com/winterbe/java8/samples/concurrent/Atomic1.java +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -3,6 +3,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.IntBinaryOperator; import java.util.stream.IntStream; /** @@ -12,23 +13,43 @@ public class Atomic1 { private static final int NUM_INCREMENTS = 10000; - private static AtomicInteger count = new AtomicInteger(0); + private static AtomicInteger atomicInt = new AtomicInteger(0); public static void main(String[] args) { testIncrement(); + testAccumulate(); + } + + private static void testAccumulate() { + atomicInt.set(0); + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> { + Runnable task = () -> { + IntBinaryOperator operator = (a, b) -> a + b; + atomicInt.accumulateAndGet(i, operator); + }; + executor.submit(task); + }); + + ConcurrentUtils.stop(executor); + + System.out.format("Accumulate: %d\n", atomicInt.get()); } private static void testIncrement() { - count.set(0); + atomicInt.set(0); ExecutorService executor = Executors.newFixedThreadPool(2); IntStream.range(0, NUM_INCREMENTS) - .forEach(i -> executor.submit(count::incrementAndGet)); + .forEach(i -> executor.submit(atomicInt::incrementAndGet)); ConcurrentUtils.stop(executor); - System.out.format("Expected=%d; Is=%d", NUM_INCREMENTS, count.get()); + System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, atomicInt.get()); } } From 463a55e9d238161473964df8f47ec6f5fac825ea Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 11 Apr 2015 09:28:57 +0200 Subject: [PATCH 32/87] Atomic update --- .../java8/samples/concurrent/Atomic1.java | 18 ++++++++++++++++++ .../samples/concurrent/ConcurrentUtils.java | 2 +- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Atomic1.java b/src/com/winterbe/java8/samples/concurrent/Atomic1.java index a23244eb..4e39aec8 100644 --- a/src/com/winterbe/java8/samples/concurrent/Atomic1.java +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -18,6 +18,24 @@ public class Atomic1 { 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() { diff --git a/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java index 70788223..6b4ac7a7 100644 --- a/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java @@ -11,7 +11,7 @@ public class ConcurrentUtils { public static void stop(ExecutorService executor) { try { executor.shutdown(); - executor.awaitTermination(5, TimeUnit.SECONDS); + executor.awaitTermination(60, TimeUnit.SECONDS); } catch (InterruptedException e) { System.err.println("termination interrupted"); From e03420cd4136e2990e3b11fc52286e780c1f431f Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 11 Apr 2015 21:33:55 +0200 Subject: [PATCH 33/87] Add LongAdder example --- .../java8/samples/concurrent/LongAdder1.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/LongAdder1.java 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()); + } +} From eac9257fa6c9fdbfb1c29b41f78049e862d67451 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 11 Apr 2015 21:50:33 +0200 Subject: [PATCH 34/87] Add LongAccumulator example --- .../samples/concurrent/LongAccumulator1.java | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java 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..a22024ee --- /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.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class LongAccumulator1 { + + private static final int SIZE = 10; + + private static LongAccumulator accumulator = new LongAccumulator((x, y) -> 2 * x + y, 1L); + + public static void main(String[] args) { + testAccumulate(); + } + + private static void testAccumulate() { + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, SIZE) + .forEach(i -> executor.submit(() -> accumulator.accumulate(i))); + + ConcurrentUtils.stop(executor); + + System.out.format("Add: %d\n", accumulator.getThenReset()); + } +} From 402225560d7e1b4fe8cdb618c2e9ae0fcaeea4d9 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sun, 12 Apr 2015 07:34:23 +0200 Subject: [PATCH 35/87] Add Semaphore example --- .../java8/samples/concurrent/Semaphore1.java | 51 +++++++++++++++++++ .../samples/concurrent/Synchronized1.java | 5 +- 2 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 src/com/winterbe/java8/samples/concurrent/Semaphore1.java 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/Synchronized1.java b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java index 06b14648..c2a4e612 100644 --- a/src/com/winterbe/java8/samples/concurrent/Synchronized1.java +++ b/src/com/winterbe/java8/samples/concurrent/Synchronized1.java @@ -19,7 +19,7 @@ public static void main(String[] args) { } private static void testSyncIncrement() { - count = 1; + count = 0; ExecutorService executor = Executors.newFixedThreadPool(2); @@ -32,7 +32,7 @@ private static void testSyncIncrement() { } private static void testNonSyncIncrement() { - count = 1; + count = 0; ExecutorService executor = Executors.newFixedThreadPool(2); @@ -51,4 +51,5 @@ private static synchronized void incrementSync() { private static void increment() { count = count + 1; } + } From c1117a9fd147a5885290cdf21cccc782062c4d0f Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 18 Apr 2015 08:05:46 +0200 Subject: [PATCH 36/87] Synchronized statement example --- .../samples/concurrent/Synchronized2.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Synchronized2.java 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; + } + } + +} From 83db0821847b37de9adc016bf0ebe3f3b9128eaf Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sun, 19 Apr 2015 08:27:56 +0200 Subject: [PATCH 37/87] Lock examples --- .../java8/samples/concurrent/Lock1.java | 46 +++++++++++++++++++ .../java8/samples/concurrent/Lock2.java | 29 ++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Lock1.java create mode 100644 src/com/winterbe/java8/samples/concurrent/Lock2.java 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..60b5ffc1 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock1.java @@ -0,0 +1,46 @@ +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..b85a1aad --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock2.java @@ -0,0 +1,29 @@ +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 { + System.out.println(lock.isLocked()); + } finally { + lock.unlock(); + } + }); + + ConcurrentUtils.stop(executor); + } + +} From 2428f6294fe5d7582c8c4ebab2c0668926009feb Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Mon, 20 Apr 2015 07:31:37 +0200 Subject: [PATCH 38/87] Lock examples --- .../winterbe/java8/samples/concurrent/Lock2.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Lock2.java b/src/com/winterbe/java8/samples/concurrent/Lock2.java index b85a1aad..d2bea9a5 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock2.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock2.java @@ -2,6 +2,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** @@ -18,11 +19,23 @@ public static void main(String[] args) { lock.lock(); try { System.out.println(lock.isLocked()); - } finally { + TimeUnit.SECONDS.sleep(1); + } + catch (InterruptedException e) { + throw new IllegalStateException(e); + } + 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); } From 4a8a7e0a300030b0093993555401a61b7c5e86ec Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Mon, 20 Apr 2015 07:56:19 +0200 Subject: [PATCH 39/87] ReadWriteLock examples --- .../java8/samples/concurrent/Lock3.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Lock3.java 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..0166b466 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock3.java @@ -0,0 +1,70 @@ +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.TimeUnit; +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 { + TimeUnit.SECONDS.sleep(1); + map.put("foo", "bar"); + } + catch (InterruptedException e) { + throw new IllegalStateException(e); + } + finally { + lock.writeLock().unlock(); + } + }); + + executor.submit(() -> { + lock.readLock().lock(); + try { + String foo = map.get("foo"); + System.out.println(foo); + TimeUnit.SECONDS.sleep(1); + } + catch (InterruptedException e) { + throw new IllegalStateException(e); + } + finally { + lock.readLock().unlock(); + } + }); + + executor.submit(() -> { + lock.readLock().lock(); + try { + String foo = map.get("foo"); + System.out.println(foo); + TimeUnit.SECONDS.sleep(1); + } + catch (InterruptedException e) { + throw new IllegalStateException(e); + } + finally { + lock.readLock().unlock(); + } + }); + + ConcurrentUtils.stop(executor); + } + +} From fe20d0c0a5b3cd712c08e4e7ca4a26f8a8c1c724 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Mon, 20 Apr 2015 17:43:49 +0200 Subject: [PATCH 40/87] StampedLock examples --- .../java8/samples/concurrent/Lock4.java | 59 +++++++++++++++++++ .../java8/samples/concurrent/Lock5.java | 56 ++++++++++++++++++ .../java8/samples/concurrent/Lock6.java | 39 ++++++++++++ 3 files changed, 154 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Lock4.java create mode 100644 src/com/winterbe/java8/samples/concurrent/Lock5.java create mode 100644 src/com/winterbe/java8/samples/concurrent/Lock6.java 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..e0265653 --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock4.java @@ -0,0 +1,59 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.StampedLock; + +/** + * @author Benjamin Winterberg + */ +public class Lock4 { + + 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.writeLock(); + try { + count++; + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } finally { + lock.unlockWrite(stamp); + } + }); + + executor.submit(() -> { + long stamp = lock.readLock(); + try { + System.out.println(Thread.currentThread().getName() + ": " + count); + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } finally { + lock.unlockRead(stamp); + } + }); + + executor.submit(() -> { + long stamp = lock.readLock(); + try { + System.out.println(Thread.currentThread().getName() + ": " + count); + TimeUnit.SECONDS.sleep(1); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } finally { + lock.unlockRead(stamp); + } + }); + + 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..5efacb5d --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/Lock5.java @@ -0,0 +1,56 @@ +package com.winterbe.java8.samples.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.StampedLock; + +/** + * @author Benjamin Winterberg + */ +public class Lock5 { + + 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.tryOptimisticRead(); + try { + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + TimeUnit.SECONDS.sleep(1); + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } finally { + lock.unlock(stamp); + } + }); + + executor.submit(() -> { + long stamp = lock.writeLock(); + try { + System.out.println("Write Lock acquired"); + incrementAndSleep(2); + } finally { + lock.unlock(stamp); + System.out.println("Write done"); + } + }); + + + ConcurrentUtils.stop(executor); + } + + private static void incrementAndSleep(int sleepSeconds) { + try { + count++; + TimeUnit.SECONDS.sleep(sleepSeconds); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } +} 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); + } + +} From e422b65b230eebaf0177225161da7ad3c486c251 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 21 Apr 2015 07:54:26 +0200 Subject: [PATCH 41/87] Simplify code --- .../java8/samples/concurrent/Lock2.java | 7 ++-- .../java8/samples/concurrent/Lock3.java | 36 +++++-------------- .../java8/samples/concurrent/Lock4.java | 28 ++++++--------- 3 files changed, 21 insertions(+), 50 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Lock2.java b/src/com/winterbe/java8/samples/concurrent/Lock2.java index d2bea9a5..a74e4e01 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock2.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock2.java @@ -18,13 +18,10 @@ public static void main(String[] args) { executor.submit(() -> { lock.lock(); try { - System.out.println(lock.isLocked()); TimeUnit.SECONDS.sleep(1); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { throw new IllegalStateException(e); - } - finally { + } finally { lock.unlock(); } }); diff --git a/src/com/winterbe/java8/samples/concurrent/Lock3.java b/src/com/winterbe/java8/samples/concurrent/Lock3.java index 0166b466..1a6e0a44 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock3.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock3.java @@ -25,44 +25,26 @@ public static void main(String[] args) { try { TimeUnit.SECONDS.sleep(1); map.put("foo", "bar"); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { throw new IllegalStateException(e); - } - finally { + } finally { lock.writeLock().unlock(); } }); - executor.submit(() -> { + Runnable readTask = () -> { lock.readLock().lock(); try { - String foo = map.get("foo"); - System.out.println(foo); + System.out.println(map.get("foo")); TimeUnit.SECONDS.sleep(1); - } - catch (InterruptedException e) { + } catch (InterruptedException e) { throw new IllegalStateException(e); - } - finally { + } finally { lock.readLock().unlock(); } - }); - - executor.submit(() -> { - lock.readLock().lock(); - try { - String foo = map.get("foo"); - System.out.println(foo); - TimeUnit.SECONDS.sleep(1); - } - catch (InterruptedException e) { - throw new IllegalStateException(e); - } - 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 index e0265653..8b06b256 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock4.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock4.java @@ -1,5 +1,7 @@ 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.TimeUnit; @@ -10,18 +12,18 @@ */ public class Lock4 { - private static int count = 0; - 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 { - count++; TimeUnit.SECONDS.sleep(1); + map.put("foo", "bar"); } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { @@ -29,29 +31,19 @@ public static void main(String[] args) { } }); - executor.submit(() -> { + Runnable readTask = () -> { long stamp = lock.readLock(); try { - System.out.println(Thread.currentThread().getName() + ": " + count); + System.out.println(map.get("foo")); TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { lock.unlockRead(stamp); } - }); - - executor.submit(() -> { - long stamp = lock.readLock(); - try { - System.out.println(Thread.currentThread().getName() + ": " + count); - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - throw new IllegalStateException(e); - } finally { - lock.unlockRead(stamp); - } - }); + }; + executor.submit(readTask); + executor.submit(readTask); ConcurrentUtils.stop(executor); } From f61cd1ba1df8377c236ca4af436a6dfe2ed6f39e Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 21 Apr 2015 17:33:52 +0200 Subject: [PATCH 42/87] Simplify code --- .../samples/concurrent/ConcurrentUtils.java | 8 ++++++++ .../java8/samples/concurrent/Lock1.java | 5 ++--- .../java8/samples/concurrent/Lock2.java | 5 +---- .../java8/samples/concurrent/Lock3.java | 9 ++------- .../java8/samples/concurrent/Lock4.java | 9 ++------- .../java8/samples/concurrent/Lock5.java | 18 ++---------------- 6 files changed, 17 insertions(+), 37 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java index 6b4ac7a7..86cfee8d 100644 --- a/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentUtils.java @@ -24,4 +24,12 @@ public static void stop(ExecutorService executor) { } } + 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/Lock1.java b/src/com/winterbe/java8/samples/concurrent/Lock1.java index 60b5ffc1..d96eba3a 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock1.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock1.java @@ -20,8 +20,7 @@ private static void increment() { lock.lock(); try { count++; - } - finally { + } finally { lock.unlock(); } } @@ -36,7 +35,7 @@ private static void testLock() { ExecutorService executor = Executors.newFixedThreadPool(2); IntStream.range(0, NUM_INCREMENTS) - .forEach(i -> executor.submit(Lock1::increment)); + .forEach(i -> executor.submit(Lock1::increment)); ConcurrentUtils.stop(executor); diff --git a/src/com/winterbe/java8/samples/concurrent/Lock2.java b/src/com/winterbe/java8/samples/concurrent/Lock2.java index a74e4e01..12757908 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock2.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock2.java @@ -2,7 +2,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** @@ -18,9 +17,7 @@ public static void main(String[] args) { executor.submit(() -> { lock.lock(); try { - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - throw new IllegalStateException(e); + ConcurrentUtils.sleep(1); } finally { lock.unlock(); } diff --git a/src/com/winterbe/java8/samples/concurrent/Lock3.java b/src/com/winterbe/java8/samples/concurrent/Lock3.java index 1a6e0a44..5e24a49b 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock3.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock3.java @@ -4,7 +4,6 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; @@ -23,10 +22,8 @@ public static void main(String[] args) { executor.submit(() -> { lock.writeLock().lock(); try { - TimeUnit.SECONDS.sleep(1); + ConcurrentUtils.sleep(1); map.put("foo", "bar"); - } catch (InterruptedException e) { - throw new IllegalStateException(e); } finally { lock.writeLock().unlock(); } @@ -36,9 +33,7 @@ public static void main(String[] args) { lock.readLock().lock(); try { System.out.println(map.get("foo")); - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - throw new IllegalStateException(e); + ConcurrentUtils.sleep(1); } finally { lock.readLock().unlock(); } diff --git a/src/com/winterbe/java8/samples/concurrent/Lock4.java b/src/com/winterbe/java8/samples/concurrent/Lock4.java index 8b06b256..4061a694 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock4.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock4.java @@ -4,7 +4,6 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.StampedLock; /** @@ -22,10 +21,8 @@ public static void main(String[] args) { executor.submit(() -> { long stamp = lock.writeLock(); try { - TimeUnit.SECONDS.sleep(1); + ConcurrentUtils.sleep(1); map.put("foo", "bar"); - } catch (InterruptedException e) { - throw new IllegalStateException(e); } finally { lock.unlockWrite(stamp); } @@ -35,9 +32,7 @@ public static void main(String[] args) { long stamp = lock.readLock(); try { System.out.println(map.get("foo")); - TimeUnit.SECONDS.sleep(1); - } catch (InterruptedException e) { - throw new IllegalStateException(e); + ConcurrentUtils.sleep(1); } finally { lock.unlockRead(stamp); } diff --git a/src/com/winterbe/java8/samples/concurrent/Lock5.java b/src/com/winterbe/java8/samples/concurrent/Lock5.java index 5efacb5d..610a491d 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock5.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock5.java @@ -2,7 +2,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.StampedLock; /** @@ -10,8 +9,6 @@ */ public class Lock5 { - private static int count = 0; - public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); @@ -21,10 +18,8 @@ public static void main(String[] args) { long stamp = lock.tryOptimisticRead(); try { System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); - TimeUnit.SECONDS.sleep(1); + ConcurrentUtils.sleep(1); System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); - } catch (InterruptedException e) { - throw new IllegalStateException(e); } finally { lock.unlock(stamp); } @@ -34,23 +29,14 @@ public static void main(String[] args) { long stamp = lock.writeLock(); try { System.out.println("Write Lock acquired"); - incrementAndSleep(2); + ConcurrentUtils.sleep(2); } finally { lock.unlock(stamp); System.out.println("Write done"); } }); - ConcurrentUtils.stop(executor); } - private static void incrementAndSleep(int sleepSeconds) { - try { - count++; - TimeUnit.SECONDS.sleep(sleepSeconds); - } catch (InterruptedException e) { - throw new IllegalStateException(e); - } - } } From bbf062daea32c0b3f01a5346b0424be94488cbaf Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Wed, 22 Apr 2015 07:49:05 +0200 Subject: [PATCH 43/87] Semaphore example --- .../java8/samples/concurrent/Semaphore2.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/Semaphore2.java 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(); + } + } + } + +} From b2d20be9d1043a1af00746c94c0509a7bc5aa100 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 30 Apr 2015 11:17:14 +0200 Subject: [PATCH 44/87] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index aa0dd99f..dee922e3 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ This repository contains all code samples from the Java 8 related posts of my [b - [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 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/) From 01dfc048f2f1ff68500f196114d2696423f3cd24 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 1 May 2015 07:17:55 +0200 Subject: [PATCH 45/87] Lock example --- src/com/winterbe/java8/samples/concurrent/Lock5.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/com/winterbe/java8/samples/concurrent/Lock5.java b/src/com/winterbe/java8/samples/concurrent/Lock5.java index 610a491d..79802230 100644 --- a/src/com/winterbe/java8/samples/concurrent/Lock5.java +++ b/src/com/winterbe/java8/samples/concurrent/Lock5.java @@ -20,6 +20,8 @@ public static void main(String[] args) { 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); } From 780bfa6672699d24453b01349b682e5fc7efeccf Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Mon, 4 May 2015 09:00:45 +0200 Subject: [PATCH 46/87] ConcurrentHashMap examples --- .../concurrent/ConcurrentHashMap1.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java 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..0a0fc9ce --- /dev/null +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java @@ -0,0 +1,33 @@ +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) { + testForEach(); + } + + 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((key, value) -> System.out.printf("key: %s; value: %s\n", key, value)); + + System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism()); + + 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()); + } + +} From d3dda84ed7b4a204b6608b1d5dcb9652f145cbc8 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 5 May 2015 08:01:51 +0200 Subject: [PATCH 47/87] Cosmetics --- src/com/winterbe/java8/samples/concurrent/Atomic1.java | 2 +- .../java8/samples/concurrent/LongAccumulator1.java | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Atomic1.java b/src/com/winterbe/java8/samples/concurrent/Atomic1.java index 4e39aec8..119e396c 100644 --- a/src/com/winterbe/java8/samples/concurrent/Atomic1.java +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -11,7 +11,7 @@ */ public class Atomic1 { - private static final int NUM_INCREMENTS = 10000; + private static final int NUM_INCREMENTS = 1000; private static AtomicInteger atomicInt = new AtomicInteger(0); diff --git a/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java b/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java index a22024ee..fa000a1b 100644 --- a/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java +++ b/src/com/winterbe/java8/samples/concurrent/LongAccumulator1.java @@ -3,6 +3,7 @@ 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; /** @@ -10,18 +11,17 @@ */ public class LongAccumulator1 { - private static final int SIZE = 10; - - private static LongAccumulator accumulator = new LongAccumulator((x, y) -> 2 * x + y, 1L); - 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, SIZE) + IntStream.range(0, 10) .forEach(i -> executor.submit(() -> accumulator.accumulate(i))); ConcurrentUtils.stop(executor); From c80d39b2560298e14a7f566779d9a6dbbe51d285 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 7 May 2015 07:20:29 +0200 Subject: [PATCH 48/87] ConcurrentHashMap examples --- .../concurrent/ConcurrentHashMap1.java | 50 +++++++++++++++++-- 1 file changed, 47 insertions(+), 3 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java index 0a0fc9ce..4acf79ab 100644 --- a/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java +++ b/src/com/winterbe/java8/samples/concurrent/ConcurrentHashMap1.java @@ -9,20 +9,64 @@ public class ConcurrentHashMap1 { public static void main(String[] args) { + System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism()); + testForEach(); + testSearch(); + testReduce(); } - private static void testForEach() { + 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); -// map.forEach((key, value) -> System.out.printf("key: %s; value: %s\n", key, value)); + System.out.println(reduced); + } - System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism()); + 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())); From 4fa2b2b6d1c49a01661e66e35f9c090b76a6a178 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Tue, 12 May 2015 07:47:21 +0200 Subject: [PATCH 49/87] Cosmetics --- src/com/winterbe/java8/samples/concurrent/Atomic1.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/com/winterbe/java8/samples/concurrent/Atomic1.java b/src/com/winterbe/java8/samples/concurrent/Atomic1.java index 119e396c..0f9d3cba 100644 --- a/src/com/winterbe/java8/samples/concurrent/Atomic1.java +++ b/src/com/winterbe/java8/samples/concurrent/Atomic1.java @@ -3,7 +3,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.IntBinaryOperator; import java.util.stream.IntStream; /** @@ -45,10 +44,8 @@ private static void testAccumulate() { IntStream.range(0, NUM_INCREMENTS) .forEach(i -> { - Runnable task = () -> { - IntBinaryOperator operator = (a, b) -> a + b; - atomicInt.accumulateAndGet(i, operator); - }; + Runnable task = () -> + atomicInt.accumulateAndGet(i, (n, m) -> n + m); executor.submit(task); }); From 9501b001a3f3186a865fbfb12c722dea175153e1 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Fri, 29 May 2015 13:37:27 +0200 Subject: [PATCH 50/87] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index dee922e3..708d37d5 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ This repository contains all code samples from the Java 8 related posts of my [b - [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/) From 1c3eaf142f149faac609c4014b53a70b403c3895 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 25 Jul 2015 07:57:20 +0200 Subject: [PATCH 51/87] Nashorn scope samples --- .../java8/samples/nashorn/Nashorn11.java | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) create mode 100644 src/com/winterbe/java8/samples/nashorn/Nashorn11.java 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..defca8ee --- /dev/null +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn11.java @@ -0,0 +1,134 @@ +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(); + } + + 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') };"); + engine.eval("foo();", new SimpleScriptContext()); + } + + 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"); + } + +} From 0c6e52cdc9e0741c99fdbe4f88c0c86cebfd1733 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Sat, 25 Jul 2015 08:12:07 +0200 Subject: [PATCH 52/87] Nashorn scope samples --- .../java8/samples/nashorn/Nashorn11.java | 27 +++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/com/winterbe/java8/samples/nashorn/Nashorn11.java b/src/com/winterbe/java8/samples/nashorn/Nashorn11.java index defca8ee..355e92eb 100644 --- a/src/com/winterbe/java8/samples/nashorn/Nashorn11.java +++ b/src/com/winterbe/java8/samples/nashorn/Nashorn11.java @@ -21,7 +21,27 @@ public static void main(String[] args) throws Exception { // test4(); // test5(); // test6(); - test7(); +// 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 { @@ -118,7 +138,10 @@ private static void test3() throws ScriptException { private static void test2() throws ScriptException { NashornScriptEngine engine = createEngine(); engine.eval("function foo() { print('bar') };"); - engine.eval("foo();", new SimpleScriptContext()); + + SimpleScriptContext context = new SimpleScriptContext(); + engine.eval("print(Function);", context); + engine.eval("foo();", context); } private static void test1() throws ScriptException { From 4796f987691f9a4da5ddd68d548b69b9b6d4c95c Mon Sep 17 00:00:00 2001 From: shubhamyeole Date: Tue, 13 Oct 2015 23:26:28 -0400 Subject: [PATCH 53/87] Added package custom --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 77642f01..f911407f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .DS_Store .idea *.iml -out \ No newline at end of file +out +/bin/ From 5ebecfcc8ce4b996bedc910c6edbea2c6ca04680 Mon Sep 17 00:00:00 2001 From: Benjamin Winterberg Date: Thu, 12 Nov 2015 09:26:10 +0100 Subject: [PATCH 54/87] Publish the original Java 8 Tutorial --- README.md | 763 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 751 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 708d37d5..8a3d73fc 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,756 @@ -Java 8 Tutorial Examples -============== +# Modern Java - A Guide to Java 8 -This repository contains all code samples from the Java 8 related posts of my [blog](http://winterbe.com): +> [“Java is still not dead—and people are starting to figure that out.”](https://twitter.com/mreinhold/status/429603588525281280) + +Welcome to my introduction to [Java 8](https://jdk8.java.net/). This tutorial guides you step by step through all new language features. Backed by short and simple code samples you'll learn how to use default interface methods, lambda expressions, method references and repeatable annotations. At the end of the article you'll be familiar with the most recent [API](http://download.java.net/jdk8/docs/api/) changes like streams, functional interfaces, map extensions and the new Date API. No walls of text - just a bunch of commented code snippets. Enjoy! + +This article was originally posted on my [blog](http://winterbe.com/posts/2014/03/16/java-8-tutorial/). + +## Default Methods for Interfaces + +Java 8 enables us to add non-abstract method implementations to interfaces by utilizing the `default` keyword. This feature is also known as **Extension Methods**. Here is our first example: + +```java +interface Formula { + double calculate(int a); + + default double sqrt(int a) { + return Math.sqrt(a); + } +} +``` + +Besides the abstract method `calculate` the interface `Formula` also defines the default method `sqrt`. Concrete classes only have to implement the abstract method `calculate`. The default method `sqrt` can be used out of the box. + +```java +Formula formula = new Formula() { + @Override + public double calculate(int a) { + return sqrt(a * 100); + } +}; + +formula.calculate(100); // 100.0 +formula.sqrt(16); // 4.0 +``` + +The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calucation of `sqrt(a * 100)`. As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8. + + +## Lambda expressions + +Let's start with a simple example of how to sort a list of strings in prior versions of Java: + +```java +List names = Arrays.asList("peter", "anna", "mike", "xenia"); + +Collections.sort(names, new Comparator() { + @Override + public int compare(String a, String b) { + return b.compareTo(a); + } +}); +``` + +The static utility method `Collections.sort` accepts a list and a comparator in order to sort the elements of the given list. You often find yourself creating anonymous comparators and pass them to the sort method. + +Instead of creating anonymous objects all day long, Java 8 comes with a much shorter syntax, **lambda expressions**: + +```java +Collections.sort(names, (String a, String b) -> { + return b.compareTo(a); +}); +``` + +As you can see the code is much shorter and easier to read. But it gets even shorter: + +```java +Collections.sort(names, (String a, String b) -> b.compareTo(a)); +``` + +For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even more shorter: + +```java +Collections.sort(names, (a, b) -> b.compareTo(a)); +``` + +The java compiler is aware of the parameter types so you can skip them as well. Let's dive deeper into how lambda expressions can be used in the wild. + + +## Functional Interfaces + +How does lambda expressions fit into Javas type system? Each lambda corresponds to a given type, specified by an interface. A so called _functional interface_ must contain **exactly one abstract method** declaration. Each lambda expression of that type will be matched to this abstract method. Since default methods are not abstract you're free to add default methods to your functional interface. + +We can use arbitrary interfaces as lambda expressions as long as the interface only contains one abstract method. To ensure that your interface meet the requirements, you should add the `@FunctionalInterface` annotation. The compiler is aware of this annotation and throws a compiler error as soon as you try to add a second abstract method declaration to the interface. + +Example: + +```java +@FunctionalInterface +interface Converter { + T convert(F from); +} +``` + +```java +Converter converter = (from) -> Integer.valueOf(from); +Integer converted = converter.convert("123"); +System.out.println(converted); // 123 +``` + +Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be ommited. + + +## Method and Constructor References + +The above example code can be further simplified by utilizing static method references: + +```java +Converter converter = Integer::valueOf; +Integer converted = converter.convert("123"); +System.out.println(converted); // 123 +``` + +Java 8 enables you to pass references of methods or constructors via the `::` keyword. The above example shows how to reference a static method. But we can also reference object methods: + +```java +class Something { + String startsWith(String s) { + return String.valueOf(s.charAt(0)); + } +} +``` + +```java +Something something = new Something(); +Converter converter = something::startsWith; +String converted = converter.convert("Java"); +System.out.println(converted); // "J" +``` + +Let's see how the `::` keyword works for constructors. First we define an example bean with different constructors: + +```java +class Person { + String firstName; + String lastName; + + Person() {} + + Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } +} +``` + +Next we specify a person factory interface to be used for creating new persons: + +```java +interface PersonFactory

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

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

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

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

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