From 257b80d8228bd9400a10924856f9603a63fbf8ae Mon Sep 17 00:00:00 2001 From: Chen Dong Date: Thu, 10 May 2018 16:35:47 +0800 Subject: [PATCH] add java8 --- .../designpatterntutorial/builder/ChDong.java | 52 +++++ .../cn/byhieg/java8/concurrent/Atomic1.java | 70 +++++++ .../java8/concurrent/CompletableFuture1.java | 22 +++ .../java8/concurrent/ConcurrentHashMap1.java | 77 ++++++++ .../java8/concurrent/ConcurrentUtils.java | 35 ++++ .../byhieg/java8/concurrent/Executors1.java | 49 +++++ .../byhieg/java8/concurrent/Executors2.java | 81 ++++++++ .../byhieg/java8/concurrent/Executors3.java | 108 +++++++++++ .../cn/byhieg/java8/concurrent/Lock1.java | 55 ++++++ .../cn/byhieg/java8/concurrent/Lock2.java | 41 ++++ .../cn/byhieg/java8/concurrent/Lock3.java | 59 ++++++ .../cn/byhieg/java8/concurrent/Lock4.java | 46 +++++ .../cn/byhieg/java8/concurrent/Lock5.java | 44 +++++ .../cn/byhieg/java8/concurrent/Lock6.java | 39 ++++ .../java8/concurrent/LongAccumulator1.java | 31 +++ .../byhieg/java8/concurrent/LongAdder1.java | 43 +++++ .../byhieg/java8/concurrent/Semaphore1.java | 51 +++++ .../byhieg/java8/concurrent/Semaphore2.java | 44 +++++ .../java8/concurrent/Synchronized1.java | 54 ++++++ .../java8/concurrent/Synchronized2.java | 39 ++++ .../cn/byhieg/java8/concurrent/Threads1.java | 61 ++++++ .../cn/byhieg/java8/lambda/Interface1.java | 35 ++++ .../java/cn/byhieg/java8/lambda/Lambda1.java | 49 +++++ .../java/cn/byhieg/java8/lambda/Lambda2.java | 47 +++++ .../java/cn/byhieg/java8/lambda/Lambda3.java | 84 ++++++++ .../java/cn/byhieg/java8/lambda/Lambda4.java | 41 ++++ .../java/cn/byhieg/java8/lambda/Lambda5.java | 32 +++ .../java/cn/byhieg/java8/lambda/Person.java | 16 ++ .../cn/byhieg/java8/misc/Annotations1.java | 47 +++++ .../byhieg/java8/misc/CheckedFunctions.java | 92 +++++++++ .../cn/byhieg/java8/misc/Concurrency1.java | 37 ++++ .../java/cn/byhieg/java8/misc/Files1.java | 104 ++++++++++ src/main/java/cn/byhieg/java8/misc/Maps1.java | 48 +++++ src/main/java/cn/byhieg/java8/misc/Math1.java | 58 ++++++ .../java/cn/byhieg/java8/misc/String1.java | 49 +++++ .../cn/byhieg/java8/nashorn/Nashorn1.java | 34 ++++ .../cn/byhieg/java8/nashorn/Nashorn10.java | 27 +++ .../cn/byhieg/java8/nashorn/Nashorn11.java | 157 +++++++++++++++ .../cn/byhieg/java8/nashorn/Nashorn2.java | 39 ++++ .../cn/byhieg/java8/nashorn/Nashorn3.java | 18 ++ .../cn/byhieg/java8/nashorn/Nashorn4.java | 18 ++ .../cn/byhieg/java8/nashorn/Nashorn5.java | 29 +++ .../cn/byhieg/java8/nashorn/Nashorn6.java | 36 ++++ .../cn/byhieg/java8/nashorn/Nashorn7.java | 43 +++++ .../cn/byhieg/java8/nashorn/Nashorn8.java | 24 +++ .../cn/byhieg/java8/nashorn/Nashorn9.java | 31 +++ .../java/cn/byhieg/java8/nashorn/Product.java | 43 +++++ .../cn/byhieg/java8/nashorn/SuperRunner.java | 13 ++ .../cn/byhieg/java8/stream/Optional1.java | 20 ++ .../cn/byhieg/java8/stream/Optional2.java | 76 ++++++++ .../java/cn/byhieg/java8/stream/Streams1.java | 102 ++++++++++ .../cn/byhieg/java8/stream/Streams10.java | 182 ++++++++++++++++++ .../cn/byhieg/java8/stream/Streams11.java | 119 ++++++++++++ .../cn/byhieg/java8/stream/Streams12.java | 88 +++++++++ .../cn/byhieg/java8/stream/Streams13.java | 26 +++ .../java/cn/byhieg/java8/stream/Streams2.java | 37 ++++ .../java/cn/byhieg/java8/stream/Streams3.java | 59 ++++++ .../java/cn/byhieg/java8/stream/Streams4.java | 37 ++++ .../java/cn/byhieg/java8/stream/Streams5.java | 138 +++++++++++++ .../java/cn/byhieg/java8/stream/Streams6.java | 57 ++++++ .../java/cn/byhieg/java8/stream/Streams7.java | 61 ++++++ .../java/cn/byhieg/java8/stream/Streams8.java | 39 ++++ .../java/cn/byhieg/java8/stream/Streams9.java | 21 ++ .../java/cn/byhieg/java8/time/LocalDate1.java | 40 ++++ .../cn/byhieg/java8/time/LocalDateTime1.java | 47 +++++ .../java/cn/byhieg/java8/time/LocalTime1.java | 72 +++++++ .../reflectiontutorial/FatherObject.java | 2 +- .../java/cn/byhieg/carl/StreamParallel.java | 44 +++++ 68 files changed, 3618 insertions(+), 1 deletion(-) create mode 100644 src/main/java/cn/byhieg/designpatterntutorial/builder/ChDong.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Atomic1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/CompletableFuture1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/ConcurrentHashMap1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/ConcurrentUtils.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Executors1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Executors2.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Executors3.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Lock1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Lock2.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Lock3.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Lock4.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Lock5.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Lock6.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/LongAccumulator1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/LongAdder1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Semaphore1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Semaphore2.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Synchronized1.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Synchronized2.java create mode 100644 src/main/java/cn/byhieg/java8/concurrent/Threads1.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Interface1.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Lambda1.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Lambda2.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Lambda3.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Lambda4.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Lambda5.java create mode 100644 src/main/java/cn/byhieg/java8/lambda/Person.java create mode 100644 src/main/java/cn/byhieg/java8/misc/Annotations1.java create mode 100644 src/main/java/cn/byhieg/java8/misc/CheckedFunctions.java create mode 100644 src/main/java/cn/byhieg/java8/misc/Concurrency1.java create mode 100644 src/main/java/cn/byhieg/java8/misc/Files1.java create mode 100644 src/main/java/cn/byhieg/java8/misc/Maps1.java create mode 100644 src/main/java/cn/byhieg/java8/misc/Math1.java create mode 100644 src/main/java/cn/byhieg/java8/misc/String1.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn1.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn10.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn11.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn2.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn3.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn4.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn5.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn6.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn7.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn8.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Nashorn9.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/Product.java create mode 100644 src/main/java/cn/byhieg/java8/nashorn/SuperRunner.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Optional1.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Optional2.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams1.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams10.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams11.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams12.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams13.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams2.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams3.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams4.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams5.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams6.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams7.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams8.java create mode 100644 src/main/java/cn/byhieg/java8/stream/Streams9.java create mode 100644 src/main/java/cn/byhieg/java8/time/LocalDate1.java create mode 100644 src/main/java/cn/byhieg/java8/time/LocalDateTime1.java create mode 100644 src/main/java/cn/byhieg/java8/time/LocalTime1.java create mode 100644 src/test/java/cn/byhieg/carl/StreamParallel.java diff --git a/src/main/java/cn/byhieg/designpatterntutorial/builder/ChDong.java b/src/main/java/cn/byhieg/designpatterntutorial/builder/ChDong.java new file mode 100644 index 0000000..386b275 --- /dev/null +++ b/src/main/java/cn/byhieg/designpatterntutorial/builder/ChDong.java @@ -0,0 +1,52 @@ +package cn.byhieg.designpatterntutorial.builder; + +public class ChDong { + private int age ; + private boolean gender; + private String name; + + + public static void main(String[] args) { + ChDong cd = new ChDong.ChDongBuilder() + .withAge(10) + .withGender(true) + .build(); + + } + public static final class ChDongBuilder { + int age; + boolean gender; + String name; + + private ChDongBuilder() { + } + + public static ChDongBuilder aChDong() { + return new ChDongBuilder(); + } + + public ChDongBuilder withAge(int age) { + this.age = age; + return this; + } + + public ChDongBuilder withGender(boolean gender) { + this.gender = gender; + return this; + } + + public ChDongBuilder withName(String name) { + this.name = name; + return this; + } + + public ChDong build() { + ChDong chDong = new ChDong(); + chDong.gender = this.gender; + chDong.age = this.age; + chDong.name = this.name; + return chDong; + } + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Atomic1.java b/src/main/java/cn/byhieg/java8/concurrent/Atomic1.java new file mode 100644 index 0000000..d512c22 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Atomic1.java @@ -0,0 +1,70 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Atomic1 { + + private static final int NUM_INCREMENTS = 1000; + + private static AtomicInteger atomicInt = new AtomicInteger(0); + + public static void main(String[] args) { + testIncrement(); + testAccumulate(); + testUpdate(); + } + + private static void testUpdate() { + atomicInt.set(0); + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> { + Runnable task = () -> + atomicInt.updateAndGet(n -> n + 2); + executor.submit(task); + }); + + ConcurrentUtils.stop(executor); + + System.out.format("Update: %d\n", atomicInt.get()); + } + + private static void testAccumulate() { + atomicInt.set(0); + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> { + Runnable task = () -> + atomicInt.accumulateAndGet(i, (n, m) -> n + m); + executor.submit(task); + }); + + ConcurrentUtils.stop(executor); + + System.out.format("Accumulate: %d\n", atomicInt.get()); + } + + private static void testIncrement() { + atomicInt.set(0); + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(atomicInt::incrementAndGet)); + + ConcurrentUtils.stop(executor); + + System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, atomicInt.get()); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/CompletableFuture1.java b/src/main/java/cn/byhieg/java8/concurrent/CompletableFuture1.java new file mode 100644 index 0000000..b6184fe --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/CompletableFuture1.java @@ -0,0 +1,22 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; + +/** + * @author Benjamin Winterberg + */ +public class CompletableFuture1 { + + public static void main(String[] args) throws ExecutionException, InterruptedException { + CompletableFuture future = new CompletableFuture<>(); + + future.complete("42"); + + future + .thenAccept(System.out::println) + .thenAccept(v -> System.out.println("done")); + + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/ConcurrentHashMap1.java b/src/main/java/cn/byhieg/java8/concurrent/ConcurrentHashMap1.java new file mode 100644 index 0000000..1d5c614 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/ConcurrentHashMap1.java @@ -0,0 +1,77 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ForkJoinPool; + +/** + * @author Benjamin Winterberg + */ +public class ConcurrentHashMap1 { + + public static void main(String[] args) { + System.out.println("Parallelism: " + ForkJoinPool.getCommonPoolParallelism()); + + testForEach(); + testSearch(); + testReduce(); + } + + private static void testReduce() { + ConcurrentHashMap map = new ConcurrentHashMap<>(); + map.putIfAbsent("foo", "bar"); + map.putIfAbsent("han", "solo"); + map.putIfAbsent("r2", "d2"); + map.putIfAbsent("c3", "p0"); + + String reduced = map.reduce(1, (key, value) -> key + "=" + value, + (s1, s2) -> s1 + ", " + s2); + + System.out.println(reduced); + } + + private static void testSearch() { + ConcurrentHashMap map = new ConcurrentHashMap<>(); + map.putIfAbsent("foo", "bar"); + map.putIfAbsent("han", "solo"); + map.putIfAbsent("r2", "d2"); + map.putIfAbsent("c3", "p0"); + + System.out.println("\nsearch()\n"); + + String result1 = map.search(1, (key, value) -> { + System.out.println(Thread.currentThread().getName()); + if (key.equals("foo") && value.equals("bar")) { + return "foobar"; + } + return null; + }); + + System.out.println(result1); + + System.out.println("\nsearchValues()\n"); + + String result2 = map.searchValues(1, value -> { + System.out.println(Thread.currentThread().getName()); + if (value.length() > 3) { + return value; + } + return null; + }); + + System.out.println(result2); + } + + private static void testForEach() { + ConcurrentHashMap map = new ConcurrentHashMap<>(); + map.putIfAbsent("foo", "bar"); + map.putIfAbsent("han", "solo"); + map.putIfAbsent("r2", "d2"); + map.putIfAbsent("c3", "p0"); + + map.forEach(1, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); +// map.forEach(5, (key, value) -> System.out.printf("key: %s; value: %s; thread: %s\n", key, value, Thread.currentThread().getName())); + + System.out.println(map.mappingCount()); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/ConcurrentUtils.java b/src/main/java/cn/byhieg/java8/concurrent/ConcurrentUtils.java new file mode 100644 index 0000000..0dc2217 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/ConcurrentUtils.java @@ -0,0 +1,35 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class ConcurrentUtils { + + public static void stop(ExecutorService executor) { + try { + executor.shutdown(); + executor.awaitTermination(60, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + System.err.println("termination interrupted"); + } + finally { + if (!executor.isTerminated()) { + System.err.println("killing non-finished tasks"); + } + executor.shutdownNow(); + } + } + + public static void sleep(int seconds) { + try { + TimeUnit.SECONDS.sleep(seconds); + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Executors1.java b/src/main/java/cn/byhieg/java8/concurrent/Executors1.java new file mode 100644 index 0000000..22a0b08 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Executors1.java @@ -0,0 +1,49 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Executors1 { + + public static void main(String[] args) { + test1(3); +// test1(7); + } + + private static void test1(long seconds) { + ExecutorService executor = Executors.newSingleThreadExecutor(); + executor.submit(() -> { + try { + TimeUnit.SECONDS.sleep(seconds); + String name = Thread.currentThread().getName(); + System.out.println("task finished: " + name); + } + catch (InterruptedException e) { + System.err.println("task interrupted"); + } + }); + stop(executor); + } + + static void stop(ExecutorService executor) { + try { + System.out.println("attempt to shutdown executor"); + executor.shutdown(); + executor.awaitTermination(5, TimeUnit.SECONDS); + } + catch (InterruptedException e) { + System.err.println("termination interrupted"); + } + finally { + if (!executor.isTerminated()) { + System.err.println("killing non-finished tasks"); + } + executor.shutdownNow(); + System.out.println("shutdown finished"); + } + } +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Executors2.java b/src/main/java/cn/byhieg/java8/concurrent/Executors2.java new file mode 100644 index 0000000..be14b36 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Executors2.java @@ -0,0 +1,81 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * @author Benjamin Winterberg + */ +public class Executors2 { + + public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException { + test1(); +// test2(); +// test3(); + } + + private static void test3() throws InterruptedException, ExecutionException, TimeoutException { + ExecutorService executor = Executors.newFixedThreadPool(1); + + Future future = executor.submit(() -> { + try { + TimeUnit.SECONDS.sleep(2); + return 123; + } + catch (InterruptedException e) { + throw new IllegalStateException("task interrupted", e); + } + }); + future.get(1, TimeUnit.SECONDS); + } + + private static void test2() throws InterruptedException, ExecutionException { + ExecutorService executor = Executors.newFixedThreadPool(1); + + Future future = executor.submit(() -> { + try { + TimeUnit.SECONDS.sleep(1); + return 123; + } + catch (InterruptedException e) { + throw new IllegalStateException("task interrupted", e); + } + }); + + executor.shutdownNow(); + future.get(); + } + + private static void test1() throws InterruptedException, ExecutionException { + ExecutorService executor = Executors.newFixedThreadPool(1); + + Future future = executor.submit(() -> { + try { + TimeUnit.SECONDS.sleep(2); + return 123; + } + catch (InterruptedException e) { + throw new IllegalStateException("task interrupted", e); + } + }); + + + + while (!future.isDone()) { + System.out.println("future done: " + future.isDone()); +// Integer result = future.get(); + } + + Integer result = future.get(); + + System.out.println("future done: " + future.isDone()); + System.out.print("result: " + result); + + executor.shutdownNow(); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Executors3.java b/src/main/java/cn/byhieg/java8/concurrent/Executors3.java new file mode 100644 index 0000000..2dc7a2c --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Executors3.java @@ -0,0 +1,108 @@ +package cn.byhieg.java8.concurrent; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Executors3 { + + public static void main(String[] args) throws InterruptedException, ExecutionException { + test1(); +// test2(); +// test3(); + +// test4(); +// test5(); + } + + private static void test5() throws InterruptedException, ExecutionException { + ExecutorService executor = Executors.newWorkStealingPool(); + + List> callables = Arrays.asList( + callable("task1", 2), + callable("task2", 1), + callable("task3", 3)); + + String result = executor.invokeAny(callables); + System.out.println(result); + + executor.shutdown(); + } + + private static Callable callable(String result, long sleepSeconds) { + return () -> { + TimeUnit.SECONDS.sleep(sleepSeconds); + return result; + }; + } + + private static void test4() throws InterruptedException { + ExecutorService executor = Executors.newWorkStealingPool(); + + List> callables = Arrays.asList( + () -> "task1", + () -> "task2", + () -> "task3"); + + executor.invokeAll(callables) + .stream() + .map(future -> { + try { + return future.get(); + } + catch (Exception e) { + throw new IllegalStateException(e); + } + }) + .forEach(System.out::println); + + executor.shutdown(); + } + + private static void test3() { + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + Runnable task = () -> { + try { + TimeUnit.SECONDS.sleep(2); + System.out.println("Scheduling: " + System.nanoTime()); + } + catch (InterruptedException e) { + System.err.println("task interrupted"); + } + }; + + executor.scheduleWithFixedDelay(task, 0, 1, TimeUnit.SECONDS); + } + + private static void test2() { + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime()); + int initialDelay = 0; + int period = 1; + executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS); + } + + private static void test1() throws InterruptedException { + ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); + + Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime()); + int delay = 3; + ScheduledFuture future = executor.schedule(task, delay, TimeUnit.SECONDS); + + TimeUnit.MILLISECONDS.sleep(1337); + + long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS); + System.out.printf("Remaining Delay: %sms\n", remainingDelay); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Lock1.java b/src/main/java/cn/byhieg/java8/concurrent/Lock1.java new file mode 100644 index 0000000..b0dc217 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Lock1.java @@ -0,0 +1,55 @@ +package cn.byhieg.java8.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 int count1 = 0; + + private static void increment() { + lock.lock(); + try { + count++; + } finally { + lock.unlock(); + } + } + + private static void increment1() { + count1++; + } + + public static void main(String[] args) { + testLock(); + } + + private static void testLock() { + count = 0; + + ExecutorService executor = Executors.newFixedThreadPool(3); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(Lock1::increment)); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(Lock1::increment1)); + + + ConcurrentUtils.stop(executor); + + System.out.println(count); + System.out.println(count1); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Lock2.java b/src/main/java/cn/byhieg/java8/concurrent/Lock2.java new file mode 100644 index 0000000..20adc26 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Lock2.java @@ -0,0 +1,41 @@ +package cn.byhieg.java8.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 Lock2 { + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(2); + + ReentrantLock lock = new ReentrantLock(); + + executor.submit(() -> { + lock.lock(); + try { +// ConcurrentUtils.sleep(1); + IntStream.range(0,100000) + .forEach(i->{ + ++i; + }); + } finally { + lock.unlock(); + } + }); + + executor.submit(() -> { + System.out.println("Locked: " + lock.isLocked()); + System.out.println("Held by me: " + lock.isHeldByCurrentThread()); + boolean locked = lock.tryLock(); + System.out.println("Lock acquired: " + locked); + }); + + ConcurrentUtils.stop(executor); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Lock3.java b/src/main/java/cn/byhieg/java8/concurrent/Lock3.java new file mode 100644 index 0000000..93eb8dc --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Lock3.java @@ -0,0 +1,59 @@ +package cn.byhieg.java8.concurrent; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +/** + * @author Benjamin Winterberg + */ +public class Lock3 { + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(2); + + Map map = new HashMap<>(); + + ReadWriteLock lock = new ReentrantReadWriteLock(); +// +// executor.submit(() -> { +// lock.writeLock().lock(); +// try { +// ConcurrentUtils.sleep(2); +// map.put("foo", "bar"); +// } finally { +// lock.writeLock().unlock(); +// } +// }); + + Runnable writeTask = ()->{ + lock.writeLock().lock(); + try { + ConcurrentUtils.sleep(1); + map.put("foo", "bar"); + } finally { + lock.writeLock().unlock(); + } + }; + + + Runnable readTask = () -> { + lock.readLock().lock(); + try { + ConcurrentUtils.sleep(1); + System.out.println(map.get("foo")); + } finally { + lock.readLock().unlock(); + } + }; +// executor.submit(readTask); + executor.submit(readTask); + executor.submit(writeTask); + + ConcurrentUtils.stop(executor); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Lock4.java b/src/main/java/cn/byhieg/java8/concurrent/Lock4.java new file mode 100644 index 0000000..7b75465 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Lock4.java @@ -0,0 +1,46 @@ +package cn.byhieg.java8.concurrent; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.StampedLock; + +/** + * @author Benjamin Winterberg + */ +public class Lock4 { + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(2); + + Map map = new HashMap<>(); + + StampedLock lock = new StampedLock(); + + executor.submit(() -> { + long stamp = lock.writeLock(); + try { + ConcurrentUtils.sleep(1); + map.put("foo", "bar"); + } finally { + lock.unlockWrite(stamp); + } + }); + + Runnable readTask = () -> { + long stamp = lock.readLock(); + try { + System.out.println(map.get("foo")); + ConcurrentUtils.sleep(1); + } finally { + lock.unlockRead(stamp); + } + }; + executor.submit(readTask); + executor.submit(readTask); + + ConcurrentUtils.stop(executor); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Lock5.java b/src/main/java/cn/byhieg/java8/concurrent/Lock5.java new file mode 100644 index 0000000..62cb4ff --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Lock5.java @@ -0,0 +1,44 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.StampedLock; + +/** + * @author Benjamin Winterberg + */ +public class Lock5 { + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(2); + + StampedLock lock = new StampedLock(); + + executor.submit(() -> { + long stamp = lock.tryOptimisticRead(); + try { + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + ConcurrentUtils.sleep(1); + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + ConcurrentUtils.sleep(2); + System.out.println("Optimistic Lock Valid: " + lock.validate(stamp)); + } finally { + lock.unlock(stamp); + } + }); + + executor.submit(() -> { + long stamp = lock.writeLock(); + try { + System.out.println("Write Lock acquired"); + ConcurrentUtils.sleep(2); + } finally { + lock.unlock(stamp); + System.out.println("Write done"); + } + }); + + ConcurrentUtils.stop(executor); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Lock6.java b/src/main/java/cn/byhieg/java8/concurrent/Lock6.java new file mode 100644 index 0000000..094cb01 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Lock6.java @@ -0,0 +1,39 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.locks.StampedLock; + +/** + * @author Benjamin Winterberg + */ +public class Lock6 { + + private static int count = 0; + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(2); + + StampedLock lock = new StampedLock(); + + executor.submit(() -> { + long stamp = lock.readLock(); + try { + if (count == 0) { + stamp = lock.tryConvertToWriteLock(stamp); + if (stamp == 0L) { + System.out.println("Could not convert to write lock"); + stamp = lock.writeLock(); + } + count = 23; + } + System.out.println(count); + } finally { + lock.unlock(stamp); + } + }); + + ConcurrentUtils.stop(executor); + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/LongAccumulator1.java b/src/main/java/cn/byhieg/java8/concurrent/LongAccumulator1.java new file mode 100644 index 0000000..3c467f1 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/LongAccumulator1.java @@ -0,0 +1,31 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.LongAccumulator; +import java.util.function.LongBinaryOperator; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class LongAccumulator1 { + + public static void main(String[] args) { + testAccumulate(); + } + + private static void testAccumulate() { + LongBinaryOperator op = (x, y) -> 2 * x + y; + LongAccumulator accumulator = new LongAccumulator(op, 1L); + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, 10) + .forEach(i -> executor.submit(() -> accumulator.accumulate(i))); + + ConcurrentUtils.stop(executor); + + System.out.format("Add: %d\n", accumulator.getThenReset()); + } +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/LongAdder1.java b/src/main/java/cn/byhieg/java8/concurrent/LongAdder1.java new file mode 100644 index 0000000..3929532 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/LongAdder1.java @@ -0,0 +1,43 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.LongAdder; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class LongAdder1 { + + private static final int NUM_INCREMENTS = 10000; + + private static LongAdder adder = new LongAdder(); + + public static void main(String[] args) { + testIncrement(); + testAdd(); + } + + private static void testAdd() { + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(() -> adder.add(2))); + + ConcurrentUtils.stop(executor); + + System.out.format("Add: %d\n", adder.sumThenReset()); + } + + private static void testIncrement() { + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(adder::increment)); + + ConcurrentUtils.stop(executor); + + System.out.format("Increment: Expected=%d; Is=%d\n", NUM_INCREMENTS, adder.sumThenReset()); + } +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Semaphore1.java b/src/main/java/cn/byhieg/java8/concurrent/Semaphore1.java new file mode 100644 index 0000000..cb76e53 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Semaphore1.java @@ -0,0 +1,51 @@ +package cn.byhieg.java8.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/main/java/cn/byhieg/java8/concurrent/Semaphore2.java b/src/main/java/cn/byhieg/java8/concurrent/Semaphore2.java new file mode 100644 index 0000000..5cc5c22 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Semaphore2.java @@ -0,0 +1,44 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Semaphore2 { + + private static Semaphore semaphore = new Semaphore(5); + + public static void main(String[] args) { + ExecutorService executor = Executors.newFixedThreadPool(10); + + IntStream.range(0, 10) + .forEach(i -> executor.submit(Semaphore2::doWork)); + + ConcurrentUtils.stop(executor); + } + + private static void doWork() { + boolean permit = false; + try { + permit = semaphore.tryAcquire(1, TimeUnit.SECONDS); + if (permit) { + System.out.println("Semaphore acquired"); + ConcurrentUtils.sleep(5); + } else { + System.out.println("Could not acquire semaphore"); + } + } catch (InterruptedException e) { + throw new IllegalStateException(e); + } finally { + if (permit) { + semaphore.release(); + } + } + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Synchronized1.java b/src/main/java/cn/byhieg/java8/concurrent/Synchronized1.java new file mode 100644 index 0000000..e42425c --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Synchronized1.java @@ -0,0 +1,54 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Synchronized1 { + + private static final int NUM_INCREMENTS = 10000; + + private static int count = 0; + + public static void main(String[] args) { + testSyncIncrement(); + testNonSyncIncrement(); + } + + private static void testSyncIncrement() { + count = 0; + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(Synchronized1::incrementSync)); + + ConcurrentUtils.stop(executor); + + System.out.println(" Sync: " + count); + } + + private static void testNonSyncIncrement() { + count = 0; + + ExecutorService executor = Executors.newFixedThreadPool(10); + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(Synchronized1::increment)); + + ConcurrentUtils.stop(executor); + + System.out.println("NonSync: " + count); + } + + private static synchronized void incrementSync() { + count = count + 1; + } + + private static void increment() { + count = count + 1; + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Synchronized2.java b/src/main/java/cn/byhieg/java8/concurrent/Synchronized2.java new file mode 100644 index 0000000..0629e98 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Synchronized2.java @@ -0,0 +1,39 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Synchronized2 { + + private static final int NUM_INCREMENTS = 10000; + + private static int count = 0; + + public static void main(String[] args) { + testSyncIncrement(); + } + + private static void testSyncIncrement() { + count = 0; + + ExecutorService executor = Executors.newFixedThreadPool(2); + + IntStream.range(0, NUM_INCREMENTS) + .forEach(i -> executor.submit(Synchronized2::incrementSync)); + + ConcurrentUtils.stop(executor); + + System.out.println(count); + } + + private static void incrementSync() { + synchronized (Synchronized2.class) { + count = count + 1; + } + } + +} diff --git a/src/main/java/cn/byhieg/java8/concurrent/Threads1.java b/src/main/java/cn/byhieg/java8/concurrent/Threads1.java new file mode 100644 index 0000000..fc38c39 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/concurrent/Threads1.java @@ -0,0 +1,61 @@ +package cn.byhieg.java8.concurrent; + +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Threads1 { + + public static void main(String[] args) { +// test1(); + test2(); +// test3(); + } + + private static void test3() { + Runnable runnable = () -> { + try { + System.out.println("Foo " + Thread.currentThread().getName()); + TimeUnit.SECONDS.sleep(1); + System.out.println("Bar " + Thread.currentThread().getName()); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + }; + + Thread thread = new Thread(runnable); + thread.start(); + } + + private static void test2() { + Runnable runnable = () -> { + try { + System.out.println("Foo " + Thread.currentThread().getName()); + Thread.sleep(1000); + System.out.println("Bar " + Thread.currentThread().getName()); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + }; + + Thread thread = new Thread(runnable); + thread.start(); + } + + private static void test1() { + Runnable runnable = () -> { + String threadName = Thread.currentThread().getName(); + System.out.println("Hello " + threadName); + }; + + runnable.run(); + + Thread thread = new Thread(runnable); + thread.start(); + + System.out.println("Done!"); + } +} diff --git a/src/main/java/cn/byhieg/java8/lambda/Interface1.java b/src/main/java/cn/byhieg/java8/lambda/Interface1.java new file mode 100644 index 0000000..08742bd --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Interface1.java @@ -0,0 +1,35 @@ +package cn.byhieg.java8.lambda; + +/** + * @author Benjamin Winterberg + */ +public class Interface1 { + + interface Formula { + double calculate(int a); + + default double sqrt(int a) { + return Math.sqrt(positive(a)); + } + + static int positive(int a) { + return a > 0 ? a : 0; + } + } + + public static void main(String[] args) { + Formula formula1 = new Formula() { + @Override + public double calculate(int a) { + return sqrt(a * 100); + } + }; + + formula1.calculate(100); // 100.0 + formula1.sqrt(-23); // 0.0 + Formula.positive(-4); // 0.0 + +// Formula formula2 = (a) -> sqrt( a * 100); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/lambda/Lambda1.java b/src/main/java/cn/byhieg/java8/lambda/Lambda1.java new file mode 100644 index 0000000..ca8a77c --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Lambda1.java @@ -0,0 +1,49 @@ +package cn.byhieg.java8.lambda; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Optional; + +/** + * @author Benjamin Winterberg + */ +public class Lambda1 { + + public static void main(String[] args) { + List names = Arrays.asList("peter", "anna", "mike", "xenia"); + + Collections.sort(names, new Comparator() { + @Override + public int compare(String a, String b) { + return b.compareTo(a); + } + }); + + Collections.sort(names, (String a, String b) -> { + return b.compareTo(a); + }); + + Collections.sort(names, (String a, String b) -> b.compareTo(a)); + + Collections.sort(names, (a, b) -> b.compareTo(a)); + + System.out.println(names); + + names.sort(Collections.reverseOrder()); + + System.out.println(names); + + List names2 = Arrays.asList("peter", null, "anna", "mike", "xenia"); + names2.sort(Comparator.nullsLast(String::compareTo)); + System.out.println(names2); + + List names3 = null; + + Optional.ofNullable(names3).ifPresent(list -> list.sort(Comparator.naturalOrder())); + + System.out.println(names3); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/lambda/Lambda2.java b/src/main/java/cn/byhieg/java8/lambda/Lambda2.java new file mode 100644 index 0000000..15032a4 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Lambda2.java @@ -0,0 +1,47 @@ +package cn.byhieg.java8.lambda; + +/** + * @author Benjamin Winterberg + */ +public class Lambda2 { + + @FunctionalInterface + public static interface Converter { + T convert(F from); + } + + static class Something { + String startsWith(String s) { + return String.valueOf(s.charAt(0)); + } + } + + interface PersonFactory

{ + P create(String firstName, String lastName); + } + + public static void main(String[] args) { + Converter integerConverter1 = (from) -> Integer.valueOf(from); + Integer converted1 = integerConverter1.convert("123"); + System.out.println(converted1); // result: 123 + + + // method reference + + Converter integerConverter2 = Integer::valueOf; + Integer converted2 = integerConverter2.convert("123"); + System.out.println(converted2); // result: 123 + + + Something something = new Something(); + + Converter stringConverter = something::startsWith; + String converted3 = stringConverter.convert("Java"); + System.out.println(converted3); // result J + + // constructor reference + + PersonFactory personFactory = Person::new; + Person person = personFactory.create("Peter", "Parker"); + } +} diff --git a/src/main/java/cn/byhieg/java8/lambda/Lambda3.java b/src/main/java/cn/byhieg/java8/lambda/Lambda3.java new file mode 100644 index 0000000..652465e --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Lambda3.java @@ -0,0 +1,84 @@ +package cn.byhieg.java8.lambda; + +import java.util.Comparator; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; + +/** + * Common standard functions from the Java API. + * + * @author Benjamin Winterberg + */ +public class Lambda3 { + + @FunctionalInterface + interface Fun { + void foo(); + } + + public static void main(String[] args) throws Exception { + + // Predicates + + Predicate 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 + + Function toInteger = Integer::valueOf; + Function backToString = toInteger.andThen(String::valueOf); + + backToString.apply("123"); // "123" + + + // Suppliers + + Supplier personSupplier = Person::new; + personSupplier.get(); // new Person + + + // Consumers + + Consumer greeter = (p) -> System.out.println("Hello, " + p.firstName); + greeter.accept(new Person("Luke", "Skywalker")); + + + + // Comparators + + 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 + + + // Runnables + + Runnable runnable = () -> System.out.println(UUID.randomUUID()); + runnable.run(); + + + // Callables + + Callable callable = UUID::randomUUID; + callable.call(); + } + +} diff --git a/src/main/java/cn/byhieg/java8/lambda/Lambda4.java b/src/main/java/cn/byhieg/java8/lambda/Lambda4.java new file mode 100644 index 0000000..1e01405 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Lambda4.java @@ -0,0 +1,41 @@ +package cn.byhieg.java8.lambda; + +/** + * @author Benjamin Winterberg + */ +public class Lambda4 { + + static int outerStaticNum; + + int outerNum; + + void testScopes() { + int num = 1; + + Lambda2.Converter stringConverter = + (from) -> String.valueOf(from + num); + + String convert = stringConverter.convert(2); + System.out.println(convert); // 3 + + Lambda2.Converter stringConverter2 = (from) -> { + outerNum = 13; + return String.valueOf(from); + }; + + String[] array = new String[1]; + Lambda2.Converter stringConverter3 = (from) -> { + array[0] = "Hi there"; + return String.valueOf(from); + }; + + stringConverter3.convert(23); + + System.out.println(array[0]); + } + + public static void main(String[] args) { + new Lambda4().testScopes(); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/lambda/Lambda5.java b/src/main/java/cn/byhieg/java8/lambda/Lambda5.java new file mode 100644 index 0000000..b70b990 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Lambda5.java @@ -0,0 +1,32 @@ +package cn.byhieg.java8.lambda; + +import java.util.HashMap; +import java.util.function.BiConsumer; + +/** + * Created by grijesh + */ +public class Lambda5 { + + //Pre-Defined Functional Interfaces + public static void main(String... args) { + + //BiConsumer Example + BiConsumer printKeyAndValue + = (key,value) -> System.out.println(key+"-"+value); + + printKeyAndValue.accept("One",1); + printKeyAndValue.accept("Two",2); + + System.out.println("##################"); + + //Java Hash-Map foreach supports BiConsumer + HashMap dummyValues = new HashMap<>(); + dummyValues.put("One", 1); + dummyValues.put("Two", 2); + dummyValues.put("Three", 3); + + dummyValues.forEach((key,value) -> System.out.println(key+"-"+value)); + + } +} diff --git a/src/main/java/cn/byhieg/java8/lambda/Person.java b/src/main/java/cn/byhieg/java8/lambda/Person.java new file mode 100644 index 0000000..380d1c0 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/lambda/Person.java @@ -0,0 +1,16 @@ +package cn.byhieg.java8.lambda; + +/** +* @author Benjamin Winterberg +*/ +public class Person { + public String firstName; + public String lastName; + + public Person() {} + + public Person(String firstName, String lastName) { + this.firstName = firstName; + this.lastName = lastName; + } +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/misc/Annotations1.java b/src/main/java/cn/byhieg/java8/misc/Annotations1.java new file mode 100644 index 0000000..2ce19ca --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/Annotations1.java @@ -0,0 +1,47 @@ +package cn.byhieg.java8.misc; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * @author Benjamin Winterberg + */ +public class Annotations1 { + + @Target({ElementType.TYPE_PARAMETER, ElementType.TYPE_USE}) + @interface MyAnnotation { + + } + + @Retention(RetentionPolicy.RUNTIME) + @interface Hints { + Hint[] value(); + } + + @Repeatable(Hints.class) + @Retention(RetentionPolicy.RUNTIME) + @interface Hint { + String value(); + } + + @Hint("hint1") + @Hint("hint2") + class Person { + + } + + public static void main(String[] args) { + Hint hint = Person.class.getAnnotation(Hint.class); + System.out.println(hint); // null + + Hints hints1 = Person.class.getAnnotation(Hints.class); + System.out.println(hints1.value().length); // 2 + + Hint[] hints2 = Person.class.getAnnotationsByType(Hint.class); + System.out.println(hints2.length); // 2 + + } +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/misc/CheckedFunctions.java b/src/main/java/cn/byhieg/java8/misc/CheckedFunctions.java new file mode 100644 index 0000000..26544c8 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/CheckedFunctions.java @@ -0,0 +1,92 @@ +package cn.byhieg.java8.misc; + +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; + +/** + * Utilities for hassle-free usage of lambda expressions who throw checked exceptions. + * + * @author Benjamin Winterberg + */ +public final class CheckedFunctions { + + @FunctionalInterface + public interface CheckedConsumer { + void accept(T input) throws Exception; + } + + @FunctionalInterface + public interface CheckedPredicate { + boolean test(T input) throws Exception; + } + + @FunctionalInterface + public interface CheckedFunction { + T apply(F input) throws Exception; + } + + /** + * Return a function which rethrows possible checked exceptions as runtime exception. + * + * @param function + * @param + * @param + * @return + */ + public static Function function(CheckedFunction function) { + return input -> { + try { + return function.apply(input); + } + catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + throw new RuntimeException(e); + } + }; + } + + /** + * Return a predicate which rethrows possible checked exceptions as runtime exception. + * + * @param predicate + * @param + * @return + */ + public static Predicate predicate(CheckedPredicate predicate) { + return input -> { + try { + return predicate.test(input); + } + catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + throw new RuntimeException(e); + } + }; + } + + /** + * Return a consumer which rethrows possible checked exceptions as runtime exception. + * + * @param consumer + * @param + * @return + */ + public static Consumer consumer(CheckedConsumer consumer) { + return input -> { + try { + consumer.accept(input); + } + catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + throw new RuntimeException(e); + } + }; + } +} diff --git a/src/main/java/cn/byhieg/java8/misc/Concurrency1.java b/src/main/java/cn/byhieg/java8/misc/Concurrency1.java new file mode 100644 index 0000000..96d012f --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/Concurrency1.java @@ -0,0 +1,37 @@ +package cn.byhieg.java8.misc; + +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * @author Benjamin Winterberg + */ +public class Concurrency1 { + + public static void main(String[] args) { + ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap<>(); + + for (int i = 0; i < 100; i++) { + concurrentHashMap.put(i, UUID.randomUUID()); + } + + int threshold = 1; + + concurrentHashMap.forEachValue(threshold, System.out::println); + + concurrentHashMap.forEach((id, uuid) -> { + if (id % 10 == 0) { + System.out.println(String.format("%s: %s", id, uuid)); + } + }); + + UUID searchResult = concurrentHashMap.search(threshold, (id, uuid) -> { + if (String.valueOf(uuid).startsWith(String.valueOf(id))) { + return uuid; + } + return null; + }); + + System.out.println(searchResult); + } +} diff --git a/src/main/java/cn/byhieg/java8/misc/Files1.java b/src/main/java/cn/byhieg/java8/misc/Files1.java new file mode 100644 index 0000000..a1a1123 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/Files1.java @@ -0,0 +1,104 @@ +package cn.byhieg.java8.misc; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @author Benjamin Winterberg + */ +public class Files1 { + + public static void main(String[] args) throws IOException { + testWalk(); + testFind(); + testList(); + testLines(); + testReader(); + testWriter(); + testReadWriteLines(); + testReaderLines(); + } + + private static void testReaderLines() throws IOException { + Path path = Paths.get("res/nashorn1.js"); + try (BufferedReader reader = Files.newBufferedReader(path)) { + long countPrints = reader + .lines() + .filter(line -> line.contains("print")) + .count(); + System.out.println(countPrints); + } + } + + private static void testWriter() throws IOException { + Path path = Paths.get("res/output.js"); + try (BufferedWriter writer = Files.newBufferedWriter(path)) { + writer.write("print('Hello World');"); + } + } + + private static void testReader() throws IOException { + Path path = Paths.get("res/nashorn1.js"); + try (BufferedReader reader = Files.newBufferedReader(path)) { + System.out.println(reader.readLine()); + } + } + + private static void testWalk() throws IOException { + Path start = Paths.get(""); + int maxDepth = 5; + try (Stream stream = Files.walk(start, maxDepth)) { + String joined = stream + .map(String::valueOf) + .filter(path -> path.endsWith(".js")) + .collect(Collectors.joining("; ")); + System.out.println("walk(): " + joined); + } + } + + private static void testFind() throws IOException { + Path start = Paths.get(""); + int maxDepth = 5; + try (Stream stream = Files.find(start, maxDepth, (path, attr) -> + String.valueOf(path).endsWith(".js"))) { + String joined = stream + .sorted() + .map(String::valueOf) + .collect(Collectors.joining("; ")); + System.out.println("find(): " + joined); + } + } + + private static void testList() throws IOException { + try (Stream stream = Files.list(Paths.get(""))) { + String joined = stream + .map(String::valueOf) + .filter(path -> !path.startsWith(".")) + .sorted() + .collect(Collectors.joining("; ")); + System.out.println("list(): " + joined); + } + } + + private static void testLines() throws IOException { + try (Stream stream = Files.lines(Paths.get("res/nashorn1.js"))) { + stream + .filter(line -> line.contains("print")) + .map(String::trim) + .forEach(System.out::println); + } + } + + private static void testReadWriteLines() throws IOException { + List lines = Files.readAllLines(Paths.get("res/nashorn1.js")); + lines.add("print('foobar');"); + Files.write(Paths.get("res", "nashorn1-modified.js"), lines); + } +} diff --git a/src/main/java/cn/byhieg/java8/misc/Maps1.java b/src/main/java/cn/byhieg/java8/misc/Maps1.java new file mode 100644 index 0000000..4ece725 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/Maps1.java @@ -0,0 +1,48 @@ +package cn.byhieg.java8.misc; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Benjamin Winterberg + */ +public class Maps1 { + + public static void main(String[] args) { + Map map = new HashMap<>(); + + for (int i = 0; i < 10; i++) { + map.putIfAbsent(i, "val" + i); + } + + map.forEach((id, val) -> System.out.println(val)); + + + map.computeIfPresent(3, (num, val) -> val + num); + System.out.println(map.get(3)); // val33 + + map.computeIfPresent(9, (num, val) -> null); + System.out.println(map.containsKey(9)); // false + + map.computeIfAbsent(23, num -> "val" + num); + System.out.println(map.containsKey(23)); // true + + map.computeIfAbsent(3, num -> "bam"); + System.out.println(map.get(3)); // val33 + + System.out.println(map.getOrDefault(42, "not found")); // not found + + map.remove(3, "val3"); + System.out.println(map.get(3)); // val33 + + map.remove(3, "val33"); + System.out.println(map.get(3)); // null + + map.merge(9, "val9", (value, newValue) -> value.concat(newValue)); + System.out.println(map.get(9)); // val9 + + map.merge(9, "concat", (value, newValue) -> value.concat(newValue)); + System.out.println(map.get(9)); // val9concat + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/misc/Math1.java b/src/main/java/cn/byhieg/java8/misc/Math1.java new file mode 100644 index 0000000..c628a88 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/Math1.java @@ -0,0 +1,58 @@ +package cn.byhieg.java8.misc; + +/** + * @author Benjamin Winterberg + */ +public class Math1 { + + public static void main(String[] args) { + testMathExact(); + testUnsignedInt(); + } + + private static void testUnsignedInt() { + try { + Integer.parseUnsignedInt("-123", 10); + } + catch (NumberFormatException e) { + System.out.println(e.getMessage()); + } + + long maxUnsignedInt = (1l << 32) - 1; + System.out.println(maxUnsignedInt); + + String string = String.valueOf(maxUnsignedInt); + + int unsignedInt = Integer.parseUnsignedInt(string, 10); + System.out.println(unsignedInt); + + String string2 = Integer.toUnsignedString(unsignedInt, 10); + System.out.println(string2); + + try { + Integer.parseInt(string, 10); + } + catch (NumberFormatException e) { + System.err.println("could not parse signed int of " + maxUnsignedInt); + } + } + + private static void testMathExact() { + System.out.println(Integer.MAX_VALUE); + System.out.println(Integer.MAX_VALUE + 1); + + try { + Math.addExact(Integer.MAX_VALUE, 1); + } + catch (ArithmeticException e) { + System.err.println(e.getMessage()); + } + + try { + Math.toIntExact(Long.MAX_VALUE); + } + catch (ArithmeticException e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/src/main/java/cn/byhieg/java8/misc/String1.java b/src/main/java/cn/byhieg/java8/misc/String1.java new file mode 100644 index 0000000..0a27010 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/misc/String1.java @@ -0,0 +1,49 @@ +package cn.byhieg.java8.misc; + +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * @author Benjamin Winterberg + */ +public class String1 { + + public static void main(String[] args) { + testJoin(); + testChars(); + testPatternPredicate(); + testPatternSplit(); + } + + private static void testChars() { + String string = "foobar:foo:bar" + .chars() + .distinct() + .mapToObj(c -> String.valueOf((char) c)) + .sorted() + .collect(Collectors.joining()); + System.out.println(string); + } + + private static void testPatternSplit() { + String string = Pattern.compile(":") + .splitAsStream("foobar:foo:bar") + .filter(s -> s.contains("bar")) + .sorted() + .collect(Collectors.joining(":")); + System.out.println(string); + } + + private static void testPatternPredicate() { + long count = Stream.of("bob@gmail.com", "alice@hotmail.com") + .filter(Pattern.compile(".*@gmail\\.com").asPredicate()) + .count(); + System.out.println(count); + } + + private static void testJoin() { + String string = String.join(":", "foobar", "foo", "bar"); + System.out.println(string); + } +} diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn1.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn1.java new file mode 100644 index 0000000..a44f94a --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn1.java @@ -0,0 +1,34 @@ +package cn.byhieg.java8.nashorn; + + +import cn.byhieg.java8.lambda.Person; + +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import java.io.FileReader; +import java.time.LocalDateTime; +import java.util.Date; + +/** + * Calling javascript functions from java with nashorn. + * + * @author Benjamin Winterberg + */ +public class Nashorn1 { + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval(new FileReader("res/nashorn1.js")); + + Invocable invocable = (Invocable) engine; + Object result = invocable.invokeFunction("fun1", "Peter Parker"); + System.out.println(result); + System.out.println(result.getClass()); + + invocable.invokeFunction("fun2", new Date()); + invocable.invokeFunction("fun2", LocalDateTime.now()); + invocable.invokeFunction("fun2", new Person()); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn10.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn10.java new file mode 100644 index 0000000..d9c0815 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn10.java @@ -0,0 +1,27 @@ +package cn.byhieg.java8.nashorn; + +import jdk.nashorn.api.scripting.NashornScriptEngine; + +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Nashorn10 { + + public static void main(String[] args) throws ScriptException, NoSuchMethodException { + NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("load('res/nashorn10.js')"); + + long t0 = System.nanoTime(); + + for (int i = 0; i < 100000; i++) { + engine.invokeFunction("testPerf"); + } + + long took = System.nanoTime() - t0; + System.out.format("Elapsed time: %d ms", TimeUnit.NANOSECONDS.toMillis(took)); + } +} diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn11.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn11.java new file mode 100644 index 0000000..2036b15 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn11.java @@ -0,0 +1,157 @@ +package cn.byhieg.java8.nashorn; + +import jdk.nashorn.api.scripting.NashornScriptEngine; + +import javax.script.Bindings; +import javax.script.ScriptContext; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import javax.script.SimpleBindings; +import javax.script.SimpleScriptContext; + +/** + * @author Benjamin Winterberg + */ +public class Nashorn11 { + + public static void main(String[] args) throws Exception { +// test1(); +// test2(); +// test3(); +// test4(); +// test5(); +// test6(); +// test7(); + test8(); + } + + private static void test8() throws ScriptException { + NashornScriptEngine engine = createEngine(); + + engine.eval("var obj = { foo: 23 };"); + + ScriptContext defaultContext = engine.getContext(); + Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context1 = new SimpleScriptContext(); + context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context2 = new SimpleScriptContext(); + context2.getBindings(ScriptContext.ENGINE_SCOPE).put("obj", defaultBindings.get("obj")); + + engine.eval("obj.foo = 44;", context1); + engine.eval("print(obj.foo);", context1); + engine.eval("print(obj.foo);", context2); + } + + private static void test7() throws ScriptException { + NashornScriptEngine engine = createEngine(); + + engine.eval("var foo = 23;"); + + ScriptContext defaultContext = engine.getContext(); + Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context1 = new SimpleScriptContext(); + context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context2 = new SimpleScriptContext(); + context2.getBindings(ScriptContext.ENGINE_SCOPE).put("foo", defaultBindings.get("foo")); + + engine.eval("foo = 44;", context1); + engine.eval("print(foo);", context1); + engine.eval("print(foo);", context2); + } + + private static void test6() throws ScriptException { + NashornScriptEngine engine = createEngine(); + + ScriptContext defaultContext = engine.getContext(); + defaultContext.getBindings(ScriptContext.GLOBAL_SCOPE).put("foo", "hello"); + + ScriptContext customContext = new SimpleScriptContext(); + customContext.setBindings(defaultContext.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.ENGINE_SCOPE); + + Bindings bindings = new SimpleBindings(); + bindings.put("foo", "world"); + customContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE); + +// engine.eval("foo = 23;"); // overrides foo in all contexts, why??? + + engine.eval("print(foo)"); // hello + engine.eval("print(foo)", customContext); // world + engine.eval("print(foo)", defaultContext); // hello + } + + private static void test5() throws ScriptException { + NashornScriptEngine engine = createEngine(); + + engine.eval("var obj = { foo: 'foo' };"); + engine.eval("function printFoo() { print(obj.foo) };"); + + ScriptContext defaultContext = engine.getContext(); + Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context1 = new SimpleScriptContext(); + context1.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context2 = new SimpleScriptContext(); + context2.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); + + engine.eval("obj.foo = 'bar';", context1); + engine.eval("printFoo();", context1); + engine.eval("printFoo();", context2); + } + + private static void test4() throws ScriptException { + NashornScriptEngine engine = createEngine(); + + engine.eval("function foo() { print('bar') };"); + + ScriptContext defaultContext = engine.getContext(); + Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context = new SimpleScriptContext(); + context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); + + engine.eval("foo();", context); + System.out.println(context.getAttribute("foo")); + } + + private static void test3() throws ScriptException { + NashornScriptEngine engine = createEngine(); + + ScriptContext defaultContext = engine.getContext(); + Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE); + + SimpleScriptContext context = new SimpleScriptContext(); + context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE); + + engine.eval("function foo() { print('bar') };", context); + engine.eval("foo();", context); + + Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); + System.out.println(bindings.get("foo")); + System.out.println(context.getAttribute("foo")); + } + + private static void test2() throws ScriptException { + NashornScriptEngine engine = createEngine(); + engine.eval("function foo() { print('bar') };"); + + SimpleScriptContext context = new SimpleScriptContext(); + engine.eval("print(Function);", context); + engine.eval("foo();", context); + } + + private static void test1() throws ScriptException { + NashornScriptEngine engine = createEngine(); + engine.eval("function foo() { print('bar') };"); + engine.eval("foo();"); + } + + private static NashornScriptEngine createEngine() { + return (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn"); + } + +} diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn2.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn2.java new file mode 100644 index 0000000..890a0eb --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn2.java @@ -0,0 +1,39 @@ +package cn.byhieg.java8.nashorn; + +import jdk.nashorn.api.scripting.ScriptObjectMirror; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import java.io.FileReader; +import java.util.Arrays; + +/** + * Calling java methods from javascript with nashorn. + * + * @author Benjamin Winterberg + */ +public class Nashorn2 { + + public static String fun(String name) { + System.out.format("Hi there from Java, %s", name); + return "greetings from java"; + } + + public static void fun2(Object object) { + System.out.println(object.getClass()); + } + + public static void fun3(ScriptObjectMirror mirror) { + System.out.println(mirror.getClassName() + ": " + Arrays.toString(mirror.getOwnKeys(true))); + } + + public static void fun4(ScriptObjectMirror person) { + System.out.println("Full Name is: " + person.callMember("getFullName")); + } + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval(new FileReader("res/nashorn2.js")); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn3.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn3.java new file mode 100644 index 0000000..3d4b264 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn3.java @@ -0,0 +1,18 @@ +package cn.byhieg.java8.nashorn; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +/** + * Working with java types from javascript. + * + * @author Benjamin Winterberg + */ +public class Nashorn3 { + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("load('res/nashorn3.js')"); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn4.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn4.java new file mode 100644 index 0000000..325b830 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn4.java @@ -0,0 +1,18 @@ +package cn.byhieg.java8.nashorn; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +/** + * Working with java types from javascript. + * + * @author Benjamin Winterberg + */ +public class Nashorn4 { + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("loadWithNewGlobal('res/nashorn4.js')"); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn5.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn5.java new file mode 100644 index 0000000..20c0a74 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn5.java @@ -0,0 +1,29 @@ +package cn.byhieg.java8.nashorn; + +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +/** + * Bind java objects to custom javascript objects. + * + * @author Benjamin Winterberg + */ +public class Nashorn5 { + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("load('res/nashorn5.js')"); + + Invocable invocable = (Invocable) engine; + + Product product = new Product(); + product.setName("Rubber"); + product.setPrice(1.99); + product.setStock(1037); + + Object result = invocable.invokeFunction("getValueOfGoods", product); + System.out.println(result); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn6.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn6.java new file mode 100644 index 0000000..da5ecf8 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn6.java @@ -0,0 +1,36 @@ +package cn.byhieg.java8.nashorn; + +import jdk.nashorn.api.scripting.ScriptObjectMirror; + +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +/** + * Using Backbone Models from Nashorn. + * + * @author Benjamin Winterberg + */ +public class Nashorn6 { + + public static void main(String[] args) throws Exception { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("load('res/nashorn6.js')"); + + Invocable invocable = (Invocable) engine; + + Product product = new Product(); + product.setName("Rubber"); + product.setPrice(1.99); + product.setStock(1337); + + ScriptObjectMirror result = (ScriptObjectMirror) + invocable.invokeFunction("calculate", product); + System.out.println(result.get("name") + ": " + result.get("valueOfGoods")); + } + + public static void getProduct(ScriptObjectMirror result) { + System.out.println(result.get("name") + ": " + result.get("valueOfGoods")); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn7.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn7.java new file mode 100644 index 0000000..1826835 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn7.java @@ -0,0 +1,43 @@ +package cn.byhieg.java8.nashorn; + +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; + +/** + * @author Benjamin Winterberg + */ +public class Nashorn7 { + + public static class Person { + private String name; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getLengthOfName() { + return name.length(); + } + } + + public static void main(String[] args) throws ScriptException, NoSuchMethodException { + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("function foo(predicate, obj) { return !!(eval(predicate)); };"); + + Invocable invocable = (Invocable) engine; + + Person person = new Person(); + person.setName("Hans"); + + String predicate = "obj.getLengthOfName() >= 4"; + Object result = invocable.invokeFunction("foo", predicate, person); + System.out.println(result); + } + +} diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn8.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn8.java new file mode 100644 index 0000000..5dac11b --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn8.java @@ -0,0 +1,24 @@ +package cn.byhieg.java8.nashorn; + + +import jdk.nashorn.api.scripting.NashornScriptEngine; + +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import cn.byhieg.java8.lambda.Person; + +/** + * @author Benjamin Winterberg + */ +public class Nashorn8 { + public static void main(String[] args) throws ScriptException, NoSuchMethodException { + NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("load('res/nashorn8.js')"); + + engine.invokeFunction("evaluate1"); // [object global] + engine.invokeFunction("evaluate2"); // [object Object] + engine.invokeFunction("evaluate3", "Foobar"); // Foobar + engine.invokeFunction("evaluate3", new Person("John", "Doe")); // [object global] <- ??????? + } + +} diff --git a/src/main/java/cn/byhieg/java8/nashorn/Nashorn9.java b/src/main/java/cn/byhieg/java8/nashorn/Nashorn9.java new file mode 100644 index 0000000..7611daa --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Nashorn9.java @@ -0,0 +1,31 @@ +package cn.byhieg.java8.nashorn; + +import jdk.nashorn.api.scripting.NashornScriptEngine; + +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Nashorn9 { + + public static void main(String[] args) throws ScriptException, NoSuchMethodException { + NashornScriptEngine engine = (NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn"); + engine.eval("load('res/nashorn9.js')"); + + long t0 = System.nanoTime(); + + double result = 0; + for (int i = 0; i < 1000; i++) { + double num = (double) engine.invokeFunction("testPerf"); + result += num; + } + + System.out.println(result > 0); + + long took = System.nanoTime() - t0; + System.out.format("Elapsed time: %d ms", TimeUnit.NANOSECONDS.toMillis(took)); + } +} diff --git a/src/main/java/cn/byhieg/java8/nashorn/Product.java b/src/main/java/cn/byhieg/java8/nashorn/Product.java new file mode 100644 index 0000000..0041792 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/Product.java @@ -0,0 +1,43 @@ +package cn.byhieg.java8.nashorn; + +/** + * @author Benjamin Winterberg + */ +public class Product { + private String name; + private double price; + private int stock; + private double valueOfGoods; + + public double getValueOfGoods() { + return valueOfGoods; + } + + public void setValueOfGoods(double valueOfGoods) { + this.valueOfGoods = valueOfGoods; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public int getStock() { + return stock; + } + + public void setStock(int stock) { + this.stock = stock; + } +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/nashorn/SuperRunner.java b/src/main/java/cn/byhieg/java8/nashorn/SuperRunner.java new file mode 100644 index 0000000..49122bc --- /dev/null +++ b/src/main/java/cn/byhieg/java8/nashorn/SuperRunner.java @@ -0,0 +1,13 @@ +package cn.byhieg.java8.nashorn; + +/** + * @author Benjamin Winterberg + */ +public class SuperRunner implements Runnable { + + @Override + public void run() { + System.out.println("super run"); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/stream/Optional1.java b/src/main/java/cn/byhieg/java8/stream/Optional1.java new file mode 100644 index 0000000..563e7ef --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Optional1.java @@ -0,0 +1,20 @@ +package cn.byhieg.java8.stream; + +import java.util.Optional; + +/** + * @author Benjamin Winterberg + */ +public class Optional1 { + + public static void main(String[] args) { + 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" + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/stream/Optional2.java b/src/main/java/cn/byhieg/java8/stream/Optional2.java new file mode 100644 index 0000000..367804c --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Optional2.java @@ -0,0 +1,76 @@ +package cn.byhieg.java8.stream; + +import java.util.Optional; +import java.util.function.Supplier; + +/** + * Examples how to avoid null checks with Optional: + * + * http://winterbe.com/posts/2015/03/15/avoid-null-checks-in-java/ + * + * @author Benjamin Winterberg + */ +public class Optional2 { + + static class Outer { + Nested nested = new Nested(); + + public Nested getNested() { + return nested; + } + } + + static class Nested { + Inner inner = new Inner(); + + public Inner getInner() { + return inner; + } + } + + static class Inner { + String foo = "boo"; + + public String getFoo() { + return foo; + } + } + + public static void main(String[] args) { + test1(); + test2(); + test3(); + } + + public static Optional resolve(Supplier resolver) { + try { + T result = resolver.get(); + return Optional.ofNullable(result); + } + catch (NullPointerException e) { + return Optional.empty(); + } + } + + private static void test3() { + Outer outer = new Outer(); + resolve(() -> outer.getNested().getInner().getFoo()) + .ifPresent(System.out::println); + } + + private static void test2() { + Optional.of(new Outer()) + .map(Outer::getNested) + .map(Nested::getInner) + .map(Inner::getFoo) + .ifPresent(System.out::println); + } + + private static void test1() { + Optional.of(new Outer()) + .flatMap(o -> Optional.ofNullable(o.nested)) + .flatMap(n -> Optional.ofNullable(n.inner)) + .flatMap(i -> Optional.ofNullable(i.foo)) + .ifPresent(System.out::println); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams1.java b/src/main/java/cn/byhieg/java8/stream/Streams1.java new file mode 100644 index 0000000..3b99e1f --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams1.java @@ -0,0 +1,102 @@ +package cn.byhieg.java8.stream; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +/** + * @author Benjamin Winterberg + */ +public class Streams1 { + + public static void main(String[] args) { + + List stringCollection = new ArrayList<>(); + stringCollection.add("ddd2"); + stringCollection.add("aaa2"); + stringCollection.add("bbb1"); + stringCollection.add("aaa1"); + stringCollection.add("bbb3"); + stringCollection.add("ccc"); + stringCollection.add("bbb2"); + stringCollection.add("ddd1"); + + + // filtering + + stringCollection + .stream() + .filter((s) -> s.startsWith("a")) + .forEach(System.out::println); + + // "aaa2", "aaa1" + + + // sorting + + stringCollection + .stream() + .sorted() + .filter((s) -> s.startsWith("a")) + .forEach(System.out::println); + + // "aaa1", "aaa2" + + + // mapping + + stringCollection + .stream() + .map(String::toUpperCase) + .sorted((a, b) -> b.compareTo(a)) + .forEach(System.out::println); + + // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1" + + + // matching + + boolean anyStartsWithA = stringCollection + .stream() + .anyMatch((s) -> s.startsWith("a")); + + System.out.println(anyStartsWithA); // true + + boolean allStartsWithA = stringCollection + .stream() + .allMatch((s) -> s.startsWith("a")); + + System.out.println(allStartsWithA); // false + + boolean noneStartsWithZ = stringCollection + .stream() + .noneMatch((s) -> s.startsWith("z")); + + System.out.println(noneStartsWithZ); // true + + + // counting + + long startsWithB = stringCollection + .stream() + .filter((s) -> s.startsWith("b")) + .count(); + + System.out.println(startsWithB); // 3 + + + // reducing + + Optional reduced = + stringCollection + .stream() + .sorted() + .reduce((s1, s2) -> s1 + "#" + s2); + + reduced.ifPresent(System.out::println); + // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2" + + + } + +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams10.java b/src/main/java/cn/byhieg/java8/stream/Streams10.java new file mode 100644 index 0000000..9d0a269 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams10.java @@ -0,0 +1,182 @@ +package cn.byhieg.java8.stream; + +import java.util.Arrays; +import java.util.IntSummaryStatistics; +import java.util.List; +import java.util.Map; +import java.util.StringJoiner; +import java.util.stream.Collector; +import java.util.stream.Collectors; + +/** + * @author Benjamin Winterberg + */ +public class Streams10 { + + static class Person { + String name; + int age; + + Person(String name, int age) { + this.name = name; + this.age = age; + } + + @Override + public String toString() { + return name; + } + } + + public static void main(String[] args) { + List persons = + Arrays.asList( + new Person("Max", 18), + new Person("Peter", 23), + new Person("Pamela", 23), + new Person("David", 12)); + +// test1(persons); +// test2(persons); +// test3(persons); +// test4(persons); +// test5(persons); +// test6(persons); +// test7(persons); +// test8(persons); + test9(persons); + } + + private static void test1(List persons) { + List filtered = + persons + .stream() + .filter(p -> p.name.startsWith("P")) + .collect(Collectors.toList()); + + System.out.println(filtered); // [Peter, Pamela] + } + + private static void test2(List persons) { + Map> personsByAge = persons + .stream() + .collect(Collectors.groupingBy(p -> p.age)); + + personsByAge + .forEach((age, p) -> System.out.format("age %s: %s\n", age, p)); + + // age 18: [Max] + // age 23:[Peter, Pamela] + // age 12:[David] + } + + private static void test3(List persons) { + Double averageAge = persons + .stream() + .collect(Collectors.averagingInt(p -> p.age)); + + System.out.println(averageAge); // 19.0 + } + + private static void test4(List persons) { + IntSummaryStatistics ageSummary = + persons + .stream() + .collect(Collectors.summarizingInt(p -> p.age)); + + System.out.println(ageSummary); + // IntSummaryStatistics{count=4, sum=76, min=12, average=19,000000, max=23} + } + + private static void test5(List persons) { + String names = persons + .stream() + .filter(p -> p.age >= 18) + .map(p -> p.name) + .collect(Collectors.joining(" and ", "In Germany ", " are of legal age.")); + + System.out.println(names); + // In Germany Max and Peter and Pamela are of legal age. + } + + private static void test6(List persons) { + Map map = persons + .stream() + .collect(Collectors.toMap( + p -> p.age, + p -> p.name, + (name1, name2) -> name1 + ";" + name2)); + + System.out.println(map); + // {18=Max, 23=Peter;Pamela, 12=David} + } + + private static void test7(List persons) { + Collector personNameCollector = + Collector.of( + () -> new StringJoiner(" | "), // supplier + (j, p) -> j.add(p.name.toUpperCase()), // accumulator + (j1, j2) -> j1.merge(j2), // combiner + StringJoiner::toString); // finisher + + String names = persons + .stream() + .collect(personNameCollector); + + System.out.println(names); // MAX | PETER | PAMELA | DAVID + } + + private static void test8(List persons) { + Collector personNameCollector = + Collector.of( + () -> { + System.out.println("supplier"); + return new StringJoiner(" | "); + }, + (j, p) -> { + System.out.format("accumulator: p=%s; j=%s\n", p, j); + j.add(p.name.toUpperCase()); + }, + (j1, j2) -> { + System.out.println("merge"); + return j1.merge(j2); + }, + j -> { + System.out.println("finisher"); + return j.toString(); + }); + + String names = persons + .stream() + .collect(personNameCollector); + + System.out.println(names); // MAX | PETER | PAMELA | DAVID + } + + private static void test9(List persons) { + Collector personNameCollector = + Collector.of( + () -> { + System.out.println("supplier"); + return new StringJoiner(" | "); + }, + (j, p) -> { + System.out.format("accumulator: p=%s; j=%s\n", p, j); + j.add(p.name.toUpperCase()); + }, + (j1, j2) -> { + System.out.println("merge"); + return j1.merge(j2); + }, + j -> { + System.out.println("finisher"); + return j.toString(); + }); + + String names = persons + .parallelStream() + .collect(personNameCollector); + + System.out.println(names); // MAX | PETER | PAMELA | DAVID + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams11.java b/src/main/java/cn/byhieg/java8/stream/Streams11.java new file mode 100644 index 0000000..4ef832b --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams11.java @@ -0,0 +1,119 @@ +package cn.byhieg.java8.stream; + +import java.util.Arrays; +import java.util.List; + +/** + * @author Benjamin Winterberg + */ +public class Streams11 { + + static class Person { + String name; + int age; + + Person(String name, int age) { + this.name = name; + this.age = age; + } + + @Override + public String toString() { + return name; + } + } + + public static void main(String[] args) { + List persons = + Arrays.asList( + new Person("Max", 18), + new Person("Peter", 23), + new Person("Pamela", 23), + new Person("David", 12)); + +// test1(persons); +// test2(persons); +// test3(persons); +// test4(persons); +// test5(persons); + test6(persons); + } + + private static void test1(List persons) { + persons + .stream() + .reduce((p1, p2) -> p1.age > p2.age ? p1 : p2) + .ifPresent(System.out::println); // Pamela + } + + private static void test2(List persons) { + Person result = + persons + .stream() + .reduce(new Person("", 0), (p1, p2) -> { + p1.age += p2.age; + p1.name += p2.name; + return p1; + }); + + System.out.format("name=%s; age=%s", result.name, result.age); + } + + private static void test3(List persons) { + Integer ageSum = persons + .stream() + .reduce(0, (sum, p) -> sum += p.age, (sum1, sum2) -> sum1 + sum2); + + System.out.println(ageSum); + } + + private static void test4(List persons) { + Integer ageSum = persons + .stream() + .reduce(0, + (sum, p) -> { + System.out.format("accumulator: sum=%s; person=%s\n", sum, p); + return sum += p.age; + }, + (sum1, sum2) -> { + System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2); + return sum1 + sum2; + }); + + System.out.println(ageSum); + } + + private static void test5(List persons) { + Integer ageSum = persons + .parallelStream() + .reduce(0, + (sum, p) -> { + System.out.format("accumulator: sum=%s; person=%s\n", sum, p); + return sum += p.age; + }, + (sum1, sum2) -> { + System.out.format("combiner: sum1=%s; sum2=%s\n", sum1, sum2); + return sum1 + sum2; + }); + + System.out.println(ageSum); + } + + private static void test6(List persons) { + Integer ageSum = persons + .parallelStream() + .reduce(0, + (sum, p) -> { + System.out.format("accumulator: sum=%s; person=%s; thread=%s\n", + sum, p, Thread.currentThread().getName()); + return sum += p.age; + }, + (sum1, sum2) -> { + System.out.format("combiner: sum1=%s; sum2=%s; thread=%s\n", + sum1, sum2, Thread.currentThread().getName()); + return sum1 + sum2; + }); + + System.out.println(ageSum); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams12.java b/src/main/java/cn/byhieg/java8/stream/Streams12.java new file mode 100644 index 0000000..210b783 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams12.java @@ -0,0 +1,88 @@ +package cn.byhieg.java8.stream; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ForkJoinPool; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Streams12 { + + public static void main(String[] args) { + List strings = Arrays.asList("a1", "a2", "b1", "c2", "c1"); + +// test1(); +// test2(strings); + test3(strings); +// test4(); + } + + private static void test4() { + List values = new ArrayList<>(100); + for (int i = 0; i < 100; i++) { + UUID uuid = UUID.randomUUID(); + values.add(uuid.toString()); + } + + // sequential + + long t0 = System.nanoTime(); + + long count = values + .parallelStream() + .sorted((s1, s2) -> { + System.out.format("sort: %s <> %s [%s]\n", s1, s2, Thread.currentThread().getName()); + return s1.compareTo(s2); + }) + .count(); + System.out.println(count); + + long t1 = System.nanoTime(); + + long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); + System.out.println(String.format("parallel sort took: %d ms", millis)); + } + + private static void test3(List strings) { + strings + .parallelStream() + .filter(s -> { + System.out.format("filter: %s [%s]\n", s, Thread.currentThread().getName()); + return true; + }) + .map(s -> { + System.out.format("map: %s [%s]\n", s, Thread.currentThread().getName()); + return s.toUpperCase(); + }) + .sorted((s1, s2) -> { + System.out.format("sort: %s <> %s [%s]\n", s1, s2, Thread.currentThread().getName()); + return s1.compareTo(s2); + }) + .forEach(s -> System.out.format("forEach: %s [%s]\n", s, Thread.currentThread().getName())); + } + + private static void test2(List strings) { + strings + .parallelStream() + .filter(s -> { + System.out.format("filter: %s [%s]\n", s, Thread.currentThread().getName()); + return true; + }) + .map(s -> { + System.out.format("map: %s [%s]\n", s, Thread.currentThread().getName()); + return s.toUpperCase(); + }) + .forEach(s -> System.out.format("forEach: %s [%s]\n", s, Thread.currentThread().getName())); + } + + private static void test1() { + // -Djava.util.concurrent.ForkJoinPool.common.parallelism=5 + + ForkJoinPool commonPool = ForkJoinPool.commonPool(); + System.out.println(commonPool.getParallelism()); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams13.java b/src/main/java/cn/byhieg/java8/stream/Streams13.java new file mode 100644 index 0000000..5f58302 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams13.java @@ -0,0 +1,26 @@ +package cn.byhieg.java8.stream; + +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Streams13 { + + public static void main(String[] args) { + SecureRandom secureRandom = new SecureRandom(new byte[]{1, 3, 3, 7}); + int[] randoms = IntStream.generate(secureRandom::nextInt) + .filter(n -> n > 0) + .limit(10) + .toArray(); + System.out.println(Arrays.toString(randoms)); + + + int[] nums = IntStream.iterate(1, n -> n * 2) + .limit(11) + .toArray(); + System.out.println(Arrays.toString(nums)); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams2.java b/src/main/java/cn/byhieg/java8/stream/Streams2.java new file mode 100644 index 0000000..96fcc1f --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams2.java @@ -0,0 +1,37 @@ +package cn.byhieg.java8.stream; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Benjamin Winterberg + */ +public class Streams2 { + + public static void main(String[] args) { + + 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"); + + + // sorting + + stringCollection + .stream() + .sorted() + .forEach(System.out::println); + + System.out.println(stringCollection); + + + + } + +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams3.java b/src/main/java/cn/byhieg/java8/stream/Streams3.java new file mode 100644 index 0000000..de01535 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams3.java @@ -0,0 +1,59 @@ +package cn.byhieg.java8.stream; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +/** + * @author Benjamin Winterberg + */ +public class Streams3 { + + public static final int MAX = 1000000; + + public static void sortSequential() { + List values = new ArrayList<>(MAX); + for (int i = 0; i < MAX; i++) { + UUID uuid = UUID.randomUUID(); + values.add(uuid.toString()); + } + + // sequential + + long t0 = System.nanoTime(); + + long count = values.stream().sorted().count(); + System.out.println(count); + + long t1 = System.nanoTime(); + + long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); + System.out.println(String.format("sequential sort took: %d ms", millis)); + } + + public static void sortParallel() { + List values = new ArrayList<>(MAX); + for (int i = 0; i < MAX; i++) { + UUID uuid = UUID.randomUUID(); + values.add(uuid.toString()); + } + + // sequential + + long t0 = System.nanoTime(); + + long count = values.parallelStream().sorted().count(); + System.out.println(count); + + long t1 = System.nanoTime(); + + long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); + System.out.println(String.format("parallel sort took: %d ms", millis)); + } + + public static void main(String[] args) { + sortSequential(); + sortParallel(); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams4.java b/src/main/java/cn/byhieg/java8/stream/Streams4.java new file mode 100644 index 0000000..aec31e7 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams4.java @@ -0,0 +1,37 @@ +package cn.byhieg.java8.stream; + +import java.util.OptionalInt; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Streams4 { + + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 1) { + System.out.println(i); + } + } + + IntStream.range(0, 10) + .forEach(i -> { + if (i % 2 == 1) System.out.println(i); + }); + + IntStream.range(0, 10) + .filter(i -> i % 2 == 1) + .forEach(System.out::println); + + OptionalInt reduced1 = + IntStream.range(0, 10) + .reduce((a, b) -> a + b); + System.out.println(reduced1.getAsInt()); + + int reduced2 = + IntStream.range(0, 10) + .reduce(7, (a, b) -> a + b); + System.out.println(reduced2); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams5.java b/src/main/java/cn/byhieg/java8/stream/Streams5.java new file mode 100644 index 0000000..bfcef81 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams5.java @@ -0,0 +1,138 @@ +package cn.byhieg.java8.stream; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; + +/** + * Testing the order of execution. + * + * @author Benjamin Winterberg + */ +public class Streams5 { + + public static void main(String[] args) { + List strings = + Arrays.asList("d2", "a2", "b1", "b3", "c"); + +// test1(strings); +// test2(strings); +// test3(strings); +// test4(strings); +// test5(strings); +// test6(strings); +// test7(strings); + test8(strings); + } + + private static void test8(List stringCollection) { + Supplier> streamSupplier = + () -> stringCollection + .stream() + .filter(s -> s.startsWith("a")); + + streamSupplier.get().anyMatch(s -> true); + streamSupplier.get().noneMatch(s -> true); + } + + // stream has already been operated upon or closed + private static void test7(List stringCollection) { + Stream stream = stringCollection + .stream() + .filter(s -> s.startsWith("a")); + + stream.anyMatch(s -> true); + stream.noneMatch(s -> true); + } + + // short-circuit + private static void test6(List stringCollection) { + stringCollection + .stream() + .map(s -> { + System.out.println("map: " + s); + return s.toUpperCase(); + }) + .anyMatch(s -> { + System.out.println("anyMatch: " + s); + return s.startsWith("A"); + }); + } + + private static void test5(List stringCollection) { + stringCollection + .stream() + .filter(s -> { + System.out.println("filter: " + s); + return s.toLowerCase().startsWith("a"); + }) + .sorted((s1, s2) -> { + System.out.printf("sort: %s; %s\n", s1, s2); + return s1.compareTo(s2); + }) + .map(s -> { + System.out.println("map: " + s); + return s.toUpperCase(); + }) + .forEach(s -> System.out.println("forEach: " + s)); + } + + // sorted = horizontal + private static void test4(List stringCollection) { + stringCollection + .stream() + .sorted((s1, s2) -> { + System.out.printf("sort: %s; %s\n", s1, s2); + return s1.compareTo(s2); + }) + .filter(s -> { + System.out.println("filter: " + s); + return s.toLowerCase().startsWith("a"); + }) + .map(s -> { + System.out.println("map: " + s); + return s.toUpperCase(); + }) + .forEach(s -> System.out.println("forEach: " + s)); + } + + private static void test3(List stringCollection) { + stringCollection + .stream() + .filter(s -> { + System.out.println("filter: " + s); + return s.startsWith("a"); + }) + .map(s -> { + System.out.println("map: " + s); + return s.toUpperCase(); + }) + .forEach(s -> System.out.println("forEach: " + s)); + } + + private static void test2(List stringCollection) { + stringCollection + .stream() + .map(s -> { + System.out.println("map: " + s); + return s.toUpperCase(); + }) + .filter(s -> { + System.out.println("filter: " + s); + return s.startsWith("A"); + }) + .forEach(s -> System.out.println("forEach: " + s)); + } + + private static void test1(List stringCollection) { + stringCollection + .stream() + .filter(s -> { + System.out.println("filter: " + s); + return true; + }) + .forEach(s -> System.out.println("forEach: " + s)); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/stream/Streams6.java b/src/main/java/cn/byhieg/java8/stream/Streams6.java new file mode 100644 index 0000000..4d9ebb8 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams6.java @@ -0,0 +1,57 @@ +package cn.byhieg.java8.stream; + +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +/** + * @author Benjamin Winterberg + */ +public class Streams6 { + + public static void main(String[] args) throws IOException { + test1(); + test2(); + test3(); + test4(); + } + + private static void test4() { + Stream + .of(new BigDecimal("1.2"), new BigDecimal("3.7")) + .mapToDouble(BigDecimal::doubleValue) + .average() + .ifPresent(System.out::println); + } + + private static void test3() { + IntStream + .range(0, 10) + .average() + .ifPresent(System.out::println); + } + + private static void test2() { + IntStream + .builder() + .add(1) + .add(3) + .add(5) + .add(7) + .add(11) + .build() + .average() + .ifPresent(System.out::println); + + } + + private static void test1() { + int[] ints = {1, 3, 5, 7, 11}; + Arrays + .stream(ints) + .average() + .ifPresent(System.out::println); + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams7.java b/src/main/java/cn/byhieg/java8/stream/Streams7.java new file mode 100644 index 0000000..f6539ee --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams7.java @@ -0,0 +1,61 @@ +package cn.byhieg.java8.stream; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.IntStream; + +/** + * @author Benjamin Winterberg + */ +public class Streams7 { + + static class Foo { + String name; + List bars = new ArrayList<>(); + + Foo(String name) { + this.name = name; + } + } + + static class Bar { + String name; + + Bar(String name) { + this.name = name; + } + } + + public static void main(String[] args) { +// test1(); + test2(); + } + + static void test2() { + IntStream.range(1, 4) + .mapToObj(num -> new Foo("Foo" + num)) + .peek(f -> IntStream.range(1, 4) + .mapToObj(num -> new Bar("Bar" + num + " <- " + f.name)) + .forEach(f.bars::add)) + .flatMap(f -> f.bars.stream()) + .forEach(b -> System.out.println(b.name)); + } + + static void test1() { + List foos = new ArrayList<>(); + + IntStream + .range(1, 4) + .forEach(num -> foos.add(new Foo("Foo" + num))); + + foos.forEach(f -> + IntStream + .range(1, 4) + .forEach(num -> f.bars.add(new Bar("Bar" + num + " <- " + f.name)))); + + foos.stream() + .flatMap(f -> f.bars.stream()) + .forEach(b -> System.out.println(b.name)); + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/stream/Streams8.java b/src/main/java/cn/byhieg/java8/stream/Streams8.java new file mode 100644 index 0000000..8a2447e --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams8.java @@ -0,0 +1,39 @@ +package cn.byhieg.java8.stream; + +import java.util.Arrays; +import java.util.stream.IntStream; +import java.util.stream.Stream; + +/** + * @author Benjamin Winterberg + */ +public class Streams8 { + + public static void main(String[] args) { + Arrays.asList("a1", "a2", "a3") + .stream() + .findFirst() + .ifPresent(System.out::println); + + Stream.of("a1", "a2", "a3") + .map(s -> s.substring(1)) + .mapToInt(Integer::parseInt) + .max() + .ifPresent(System.out::println); + + IntStream.range(1, 4) + .mapToObj(i -> "a" + i) + .forEach(System.out::println); + + Arrays.stream(new int[] {1, 2, 3}) + .map(n -> 2 * n + 1) + .average() + .ifPresent(System.out::println); + + Stream.of(1.0, 2.0, 3.0) + .mapToInt(Double::intValue) + .mapToObj(i -> "a" + i) + .forEach(System.out::println); + + } +} diff --git a/src/main/java/cn/byhieg/java8/stream/Streams9.java b/src/main/java/cn/byhieg/java8/stream/Streams9.java new file mode 100644 index 0000000..4af0630 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/stream/Streams9.java @@ -0,0 +1,21 @@ +package cn.byhieg.java8.stream; + +import java.util.Arrays; + +/** + * @author Benjamin Winterberg + */ +public class Streams9 { + + public static void main(String[] args) { + Arrays.asList("a1", "a2", "b1", "c2", "c1") + .stream() + .filter(s -> s.startsWith("c")) + .map(String::toUpperCase) + .sorted() + .forEach(System.out::println); + + // C1 + // C2 + } +} diff --git a/src/main/java/cn/byhieg/java8/time/LocalDate1.java b/src/main/java/cn/byhieg/java8/time/LocalDate1.java new file mode 100644 index 0000000..b41d112 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/time/LocalDate1.java @@ -0,0 +1,40 @@ +package cn.byhieg.java8.time; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.Month; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.time.temporal.ChronoUnit; +import java.util.Locale; + +/** + * @author Benjamin Winterberg + */ +public class LocalDate1 { + + public static void main(String[] args) { + LocalDate today = LocalDate.now(); + LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS); + LocalDate yesterday = tomorrow.minusDays(2); + + System.out.println(today); + System.out.println(tomorrow); + System.out.println(yesterday); + + LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); + DayOfWeek dayOfWeek = independenceDay.getDayOfWeek(); + System.out.println(dayOfWeek); // FRIDAY + + DateTimeFormatter germanFormatter = + DateTimeFormatter + .ofLocalizedDate(FormatStyle.MEDIUM) + .withLocale(Locale.GERMAN); + + LocalDate xmas = LocalDate.parse("24.12.2014", germanFormatter); + System.out.println(xmas); // 2014-12-24 + + + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/time/LocalDateTime1.java b/src/main/java/cn/byhieg/java8/time/LocalDateTime1.java new file mode 100644 index 0000000..8f2447d --- /dev/null +++ b/src/main/java/cn/byhieg/java8/time/LocalDateTime1.java @@ -0,0 +1,47 @@ +package cn.byhieg.java8.time; + +import java.time.DayOfWeek; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.Month; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoField; +import java.util.Date; + +/** + * @author Benjamin Winterberg + */ +public class LocalDateTime1 { + + public static void main(String[] args) { + + LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59); + + DayOfWeek dayOfWeek = sylvester.getDayOfWeek(); + System.out.println(dayOfWeek); // WEDNESDAY + + Month month = sylvester.getMonth(); + System.out.println(month); // DECEMBER + + long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY); + System.out.println(minuteOfDay); // 1439 + + Instant instant = sylvester + .atZone(ZoneId.systemDefault()) + .toInstant(); + + Date legacyDate = Date.from(instant); + System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014 + + + DateTimeFormatter formatter = + DateTimeFormatter + .ofPattern("MMM dd, yyyy - HH:mm"); + + LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter); + String string = parsed.format(formatter); + System.out.println(string); // Nov 03, 2014 - 07:13 + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/java8/time/LocalTime1.java b/src/main/java/cn/byhieg/java8/time/LocalTime1.java new file mode 100644 index 0000000..b022f53 --- /dev/null +++ b/src/main/java/cn/byhieg/java8/time/LocalTime1.java @@ -0,0 +1,72 @@ +package cn.byhieg.java8.time; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.time.temporal.ChronoUnit; +import java.util.Date; +import java.util.Locale; + +/** + * @author Benjamin Winterberg + */ +public class LocalTime1 { + + public static void main(String[] args) { + + // get the current time + Clock clock = Clock.systemDefaultZone(); + long t0 = clock.millis(); + System.out.println(t0); + + Instant instant = clock.instant(); + Date legacyDate = Date.from(instant); + + + ZoneId zone1 = ZoneId.of("Europe/Berlin"); + ZoneId zone2 = ZoneId.of("Brazil/East"); + + System.out.println(zone1.getRules()); + System.out.println(zone2.getRules()); + + // time + LocalTime now1 = LocalTime.now(zone1); + LocalTime now2 = LocalTime.now(zone2); + + System.out.println(now1); + System.out.println(now2); + + System.out.println(now1.isBefore(now2)); // false + + long hoursBetween = ChronoUnit.HOURS.between(now1, now2); + long minutesBetween = ChronoUnit.MINUTES.between(now1, now2); + System.out.println(hoursBetween); + System.out.println(minutesBetween); + + + // create time + + LocalTime now = LocalTime.now(); + System.out.println(now); + + LocalTime late = LocalTime.of(23, 59, 59); + System.out.println(late); + + DateTimeFormatter germanFormatter = + DateTimeFormatter + .ofLocalizedTime(FormatStyle.SHORT) + .withLocale(Locale.GERMAN); + + LocalTime leetTime = LocalTime.parse("13:37", germanFormatter); + System.out.println(leetTime); + + + // to legacy date + + + } + +} \ No newline at end of file diff --git a/src/main/java/cn/byhieg/reflectiontutorial/FatherObject.java b/src/main/java/cn/byhieg/reflectiontutorial/FatherObject.java index 3e933b4..44a8e28 100644 --- a/src/main/java/cn/byhieg/reflectiontutorial/FatherObject.java +++ b/src/main/java/cn/byhieg/reflectiontutorial/FatherObject.java @@ -7,7 +7,7 @@ public abstract class FatherObject implements Runnable{ - protected String father = ""; + protected String father = ""; public void doSomething(){ System.out.println("εšδΊ‹ζƒ…......"); } diff --git a/src/test/java/cn/byhieg/carl/StreamParallel.java b/src/test/java/cn/byhieg/carl/StreamParallel.java new file mode 100644 index 0000000..f69acb1 --- /dev/null +++ b/src/test/java/cn/byhieg/carl/StreamParallel.java @@ -0,0 +1,44 @@ +package cn.byhieg.carl; + +import cn.byhieg.collectiontutorial.listtutorial.ArrayListDemo; +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; + +public class StreamParallel extends TestCase { + + public void testSteam() throws Exception { + int max = 1000000; + List values = new ArrayList<>(max); + IntStream.range(0,max).forEach(i->{ + values.add(UUID.randomUUID().toString()); + }); + testSteam(values); + testParallel(values); + } + + private void testSteam(List values) { + 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("steam sort took: %d ms", millis)); + } + + public void testParallel(List values ){ + 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)); + } + + +}