Skip to content

Commit 679d561

Browse files
authored
Merge pull request #1 from winterbe/master
Sync with original repo
2 parents e0b308a + 6dd0e09 commit 679d561

3 files changed

Lines changed: 53 additions & 19 deletions

File tree

LICENSE

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
The MIT License (MIT)
22

3-
Copyright (c) 2014 Benjamin Winterberg
3+
Copyright (c) 2016 Benjamin Winterberg
44

55
Permission is hereby granted, free of charge, to any person obtaining a copy
66
of this software and associated documentation files (the "Software"), to deal
@@ -18,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1818
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1919
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2020
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21-
SOFTWARE.
21+
SOFTWARE.

README.md

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ formula.calculate(100); // 100.0
7373
formula.sqrt(16); // 4.0
7474
```
7575

76-
The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calucation of `sqrt(a * 100)`. As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8.
76+
The formula is implemented as an anonymous object. The code is quite verbose: 6 lines of code for such a simple calculation of `sqrt(a * 100)`. As we'll see in the next section, there's a much nicer way of implementing single method objects in Java 8.
7777

7878

7979
## Lambda expressions
@@ -107,7 +107,7 @@ As you can see the code is much shorter and easier to read. But it gets even sho
107107
Collections.sort(names, (String a, String b) -> b.compareTo(a));
108108
```
109109

110-
For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even more shorter:
110+
For one line method bodies you can skip both the braces `{}` and the `return` keyword. But it gets even shorter:
111111

112112
```java
113113
names.sort((a, b) -> b.compareTo(a));
@@ -118,7 +118,7 @@ List now has a `sort` method. Also the java compiler is aware of the parameter t
118118

119119
## Functional Interfaces
120120

121-
How does lambda expressions fit into Javas type system? Each lambda corresponds to a given type, specified by an interface. A so called _functional interface_ must contain **exactly one abstract method** declaration. Each lambda expression of that type will be matched to this abstract method. Since default methods are not abstract you're free to add default methods to your functional interface.
121+
How does lambda expressions fit into Java's type system? Each lambda corresponds to a given type, specified by an interface. A so called _functional interface_ must contain **exactly one abstract method** declaration. Each lambda expression of that type will be matched to this abstract method. Since default methods are not abstract you're free to add default methods to your functional interface.
122122

123123
We can use arbitrary interfaces as lambda expressions as long as the interface only contains one abstract method. To ensure that your interface meet the requirements, you should add the `@FunctionalInterface` annotation. The compiler is aware of this annotation and throws a compiler error as soon as you try to add a second abstract method declaration to the interface.
124124

@@ -137,7 +137,7 @@ Integer converted = converter.convert("123");
137137
System.out.println(converted); // 123
138138
```
139139

140-
Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be ommited.
140+
Keep in mind that the code is also valid if the `@FunctionalInterface` annotation would be omitted.
141141

142142

143143
## Method and Constructor References
@@ -239,7 +239,7 @@ Writing to `num` from within the lambda expression is also prohibited.
239239

240240
### Accessing fields and static variables
241241

242-
In constrast to local variables we have both read and write access to instance fields and static variables from within lambda expressions. This behaviour is well known from anonymous objects.
242+
In contrast to local variables, we have both read and write access to instance fields and static variables from within lambda expressions. This behaviour is well known from anonymous objects.
243243

244244
```java
245245
class Lambda4 {
@@ -267,7 +267,7 @@ Remember the formula example from the first section? Interface `Formula` defines
267267
Default methods **cannot** be accessed from within lambda expressions. The following code does not compile:
268268

269269
```java
270-
Formula formula = (a) -> sqrt( a * 100);
270+
Formula formula = (a) -> sqrt(a * 100);
271271
```
272272

273273

@@ -316,7 +316,7 @@ personSupplier.get(); // new Person
316316

317317
### Consumers
318318

319-
Consumers represents operations to be performed on a single input argument.
319+
Consumers represent operations to be performed on a single input argument.
320320

321321
```java
322322
Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);
@@ -339,7 +339,7 @@ comparator.reversed().compare(p1, p2); // < 0
339339

340340
## Optionals
341341

342-
Optionals are not functional interfaces, instead it's a nifty utility to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work.
342+
Optionals are not functional interfaces, but nifty utilities to prevent `NullPointerException`. It's an important concept for the next section, so let's have a quick look at how Optionals work.
343343

344344
Optional is a simple container for a value which may be null or non-null. Think of a method which may return a non-null result but sometimes return nothing. Instead of returning `null` you return an `Optional` in Java 8.
345345

@@ -355,9 +355,9 @@ optional.ifPresent((s) -> System.out.println(s.charAt(0))); // "b"
355355

356356
## Streams
357357

358-
A `java.util.Stream` represents a sequence of elements on which one or more operations can be performed. Stream operations are either _intermediate_ or _terminal_. While terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a `java.util.Collection` like lists or sets (maps are not supported). Stream operations can either be executed sequential or parallel.
358+
A `java.util.Stream` represents a sequence of elements on which one or more operations can be performed. Stream operations are either _intermediate_ or _terminal_. While terminal operations return a result of a certain type, intermediate operations return the stream itself so you can chain multiple method calls in a row. Streams are created on a source, e.g. a `java.util.Collection` like lists or sets (maps are not supported). Stream operations can either be executed sequentially or parallely.
359359

360-
> You should also check out [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API.
360+
> Streams are extremely powerful, so I wrote a separate [Java 8 Streams Tutorial](http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/). You should also check out [Stream.js](https://github.com/winterbe/streamjs), a JavaScript port of the Java 8 Streams API.
361361
362362
Let's first look how sequential streams work. First we create a sample source in form of a list of strings:
363363

@@ -482,7 +482,7 @@ reduced.ifPresent(System.out::println);
482482

483483
## Parallel Streams
484484

485-
As mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed concurrent on multiple threads.
485+
As mentioned above streams can be either sequential or parallel. Operations on sequential streams are performed on a single thread while operations on parallel streams are performed concurrently on multiple threads.
486486

487487
The following example demonstrates how easy it is to increase the performance by using parallel streams.
488488

@@ -535,7 +535,9 @@ As you can see both code snippets are almost identical but the parallel sort is
535535

536536
## Maps
537537

538-
As already mentioned maps don't support streams. Instead maps now support various new and useful methods for doing common tasks.
538+
As already mentioned maps do not directly support streams. There's no `stream()` method available on the `Map` interface itself, however you can create specialized streams upon the keys, values or entries of a map via `map.keySet().stream()`, `map.values().stream()` and `map.entrySet().stream()`.
539+
540+
Furthermore maps support various new and useful methods for doing common tasks.
539541

540542
```java
541543
Map<Integer, String> map = new HashMap<>();
@@ -600,7 +602,7 @@ Java 8 contains a brand new date and time API under the package `java.time`. The
600602

601603
### Clock
602604

603-
Clock provides access to the current date and time. Clocks are aware of a timezone and may be used instead of `System.currentTimeMillis()` to retrieve the current milliseconds. Such an instantaneous point on the time-line is also represented by the class `Instant`. Instants can be used to create legacy `java.util.Date` objects.
605+
Clock provides access to the current date and time. Clocks are aware of a timezone and may be used instead of `System.currentTimeMillis()` to retrieve the current time in milliseconds since Unix EPOCH. Such an instantaneous point on the time-line is also represented by the class `Instant`. Instants can be used to create legacy `java.util.Date` objects.
604606

605607
```java
606608
Clock clock = Clock.systemDefaultZone();
@@ -644,7 +646,7 @@ System.out.println(hoursBetween); // -3
644646
System.out.println(minutesBetween); // -239
645647
```
646648

647-
LocalTime comes with various factory method to simplify the creation of new instances, including parsing of time strings.
649+
LocalTime comes with various factory methods to simplify the creation of new instances, including parsing of time strings.
648650

649651
```java
650652
LocalTime late = LocalTime.of(23, 59, 59);
@@ -661,7 +663,7 @@ System.out.println(leetTime); // 13:37
661663

662664
### LocalDate
663665

664-
LocalDate represents a distinct date, e.g. 2014-03-11. It's immutable and works exactly analog to LocalTime. The sample demonstrates how to calculate new dates by adding or substracting days, months or years. Keep in mind that each manipulation returns a new instance.
666+
LocalDate represents a distinct date, e.g. 2014-03-11. It's immutable and works exactly analog to LocalTime. The sample demonstrates how to calculate new dates by adding or subtracting days, months or years. Keep in mind that each manipulation returns a new instance.
665667

666668
```java
667669
LocalDate today = LocalDate.now();
@@ -727,7 +729,7 @@ System.out.println(string); // Nov 03, 2014 - 07:13
727729

728730
Unlike `java.text.NumberFormat` the new `DateTimeFormatter` is immutable and **thread-safe**.
729731

730-
For details on the pattern syntax read [here](http://download.java.net/jdk8/docs/api/java/time/format/DateTimeFormatter.html).
732+
For details on the pattern syntax read [here](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html).
731733

732734

733735
## Annotations
@@ -763,7 +765,7 @@ class Person {}
763765
class Person {}
764766
```
765767

766-
Using variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation informations via reflection.
768+
Using variant 2 the java compiler implicitly sets up the `@Hints` annotation under the hood. That's important for reading annotation information via reflection.
767769

768770
```java
769771
Hint hint = Person.class.getAnnotation(Hint.class);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.winterbe.java8.samples.lambda;
2+
3+
import java.util.HashMap;
4+
import java.util.function.BiConsumer;
5+
6+
/**
7+
* Created by grijesh
8+
*/
9+
public class Lambda5 {
10+
11+
//Pre-Defined Functional Interfaces
12+
public static void main(String... args) {
13+
14+
//BiConsumer Example
15+
BiConsumer<String,Integer> printKeyAndValue
16+
= (key,value) -> System.out.println(key+"-"+value);
17+
18+
printKeyAndValue.accept("One",1);
19+
printKeyAndValue.accept("Two",2);
20+
21+
System.out.println("##################");
22+
23+
//Java Hash-Map foreach supports BiConsumer
24+
HashMap<String, Integer> dummyValues = new HashMap<>();
25+
dummyValues.put("One", 1);
26+
dummyValues.put("Two", 2);
27+
dummyValues.put("Three", 3);
28+
29+
dummyValues.forEach((key,value) -> System.out.println(key+"-"+value));
30+
31+
}
32+
}

0 commit comments

Comments
 (0)