Skip to content

Commit 0c3bdee

Browse files
committed
Create the sheet
1 parent 06f371d commit 0c3bdee

File tree

1 file changed

+324
-0
lines changed

1 file changed

+324
-0
lines changed

README.md

Lines changed: 324 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,324 @@
1+
2+
# JAVA 8 - Cheat Sheet
3+
4+
## Lambda Expression
5+
```java
6+
(int a) -> a * 2; // Calculate the double of a
7+
a -> a * 2; // or simply without type
8+
```
9+
```java
10+
(a, b) -> a + b; // Sum of 2 parameters
11+
```
12+
13+
If the lambda is more than one expression we can use `{ }` and `return`
14+
15+
```java
16+
(x, y) -> {
17+
int sum = x + y;
18+
int avg = sum / 2;
19+
return avg;
20+
}
21+
```
22+
23+
A lambda expression cannot stand alone in Java, it need to be associated to a functional interface.
24+
25+
```java
26+
interface MyMath {
27+
int getDoubleOf(int a);
28+
}
29+
30+
MyMath d = a -> a * 2; // associated to the interface
31+
d.getDoubleOf(4); // is 8
32+
```
33+
34+
## Collections
35+
36+
37+
**sort** `sort(list, comparator)`
38+
39+
```java
40+
list.sort(Comparator.comparing(n -> n.length()));
41+
//> [Bohr, Tesla, Darwin, Newton, Galilei, Einstein]
42+
```
43+
44+
**removeIf**
45+
46+
```java
47+
list.removeIf(w -> w.length() < 6);
48+
//> [Darwin, Galilei, Einstein, Newton]
49+
```
50+
51+
**Merge**
52+
`merge(key, value, remappingFunction)`
53+
54+
```java
55+
Map<String, String> names = new HashMap<>();
56+
names.put("Albert", "Ein?");
57+
names.put("Marie", "Curie");
58+
names.put("Max", "Plank");
59+
60+
// Value "Albert" exists
61+
// {Marie=Curie, Max=Plank, Albert=Einstein}
62+
names.merge("Albert", "stein", (old, val) -> old.substring(0, 3) + val);
63+
64+
// Value "Newname" don't exists
65+
// {Marie=Curie, Newname=stein, Max=Plank, Albert=Einstein}
66+
names.merge("Newname", "stein", (old, val) -> old.substring(0, 3) + val);
67+
```
68+
69+
70+
## Method Expressions `Class::staticMethod`
71+
72+
Allows to reference methods (and constructors) without executing them
73+
74+
```java
75+
// Lambda Form:
76+
getPrimes(numbers, a -> StaticMethod.isPrime(a));
77+
78+
// Method Reference:
79+
getPrimes(numbers, StaticMethod::isPrime);
80+
```
81+
82+
| Method Reference | Lambda Form |
83+
| ---------------- | ----------- |
84+
| `StaticMethod::isPrime` | `n -> StaticMethod.isPrime(n)` |
85+
| `String::toUpperCase` | `(String w) -> w.toUpperCase()` |
86+
| `String::compareTo` | `(String s, String t) -> s.compareTo(t)` |
87+
| `System.out::println` | `x -> System.out.println(x)` |
88+
| `Double::new` | `n -> new Double(n)` |
89+
| `String[]::new` | `(int n) -> new String[n]` |
90+
91+
## Streams
92+
93+
Similar to collections, but
94+
95+
- They don't store their own data
96+
- The data comes from elsewhere (collection, file, db, web, ...)
97+
- *immutable* (produce new streams)
98+
- *lazy* (only computes what is necessary !)
99+
100+
```java
101+
// Will compute just 3 "filter"
102+
Stream<String> longNames = list
103+
.filter(n -> n.length() > 8)
104+
.limit(3);
105+
```
106+
107+
**Create a new stream**
108+
109+
```java
110+
Stream<Integer> stream = Stream.of(1, 2, 3, 5, 7, 11);
111+
Stream<String> stream = Stream.of("Jazz", "Blues", "Rock");
112+
Stream<String> stream = Stream.of(myArray); // or from an array
113+
list.stream(); // or from a list
114+
115+
// Infinit stream [0; inf[
116+
Stream<Integer> integers = Stream.iterate(0, n -> n + 1);
117+
```
118+
119+
**Collecting results**
120+
121+
```java
122+
// Collect into an array (::new is the constructor reference)
123+
String[] myArray = stream.toArray(String[]::new);
124+
125+
// Collect into a List or Set
126+
List<String> myList = stream.collect(Collectors.toList());
127+
Set<String> mySet = stream.collect(Collectors.toSet());
128+
129+
// Collect into a String
130+
String str = list.collect(Collectors.joining(", "));
131+
```
132+
133+
**map** `map(mapper)`<br>
134+
Applying a function to each element
135+
136+
```java
137+
// Apply "toLowerCase" for each element
138+
res = stream.map(w -> w.toLowerCase());
139+
res = stream.map(String::toLowerCase);
140+
//> bohr darwin galilei tesla einstein newton
141+
142+
res = Stream.of(1,2,3,4,5).map(x -> x + 1);
143+
//> 2 3 4 5 6
144+
```
145+
146+
**filter** `filter(predicate)`<br>
147+
Retains elements that match the predicate
148+
149+
```java
150+
// Filter elements that begin with "E"
151+
res = stream.filter(n -> n.substring(0, 1).equals("E"));
152+
//> Einstein
153+
154+
res = Stream.of(1,2,3,4,5).filter(x -> x < 3);
155+
//> 2 3
156+
```
157+
158+
**reduce**<br>
159+
Reduce the elements to a single value
160+
161+
```java
162+
String reduced = stream
163+
.reduce("", (acc, el) -> acc + "|" + el);
164+
//> |Bohr|Darwin|Galilei|Tesla|Einstein|Newton
165+
```
166+
167+
**limit** `limit(maxSize)`
168+
The n first elements
169+
170+
```java
171+
res = stream.limit(3);
172+
//> Bohr Darwin Galilei
173+
```
174+
175+
**skip**
176+
Discarding the first n elements
177+
178+
```java
179+
res = strem.skip(2); // skip Bohr and Darwin
180+
//> Galilei Tesla Einstein Newton
181+
```
182+
183+
**distinct**
184+
Remove duplicated elemetns
185+
186+
```java
187+
res = Stream.of(1,0,0,1,0,1).distinct();
188+
//> 1 0
189+
```
190+
191+
**sorted**
192+
Sort elements (must be *Comparable*)
193+
194+
```java
195+
res = stream.sorted();
196+
//> Bohr Darwin Einstein Galilei Newton Tesla
197+
```
198+
199+
**allMatch**
200+
201+
```java
202+
// Check if there is a "e" in each elements
203+
boolean res = words.allMatch(n -> n.contains("e"));
204+
```
205+
206+
anyMatch: Check if there is a "e" in an element<br>
207+
noneMatch: Check if there is no "e" in elements
208+
209+
**parallel**
210+
Returns an equivalent stream that is parallel
211+
212+
**findAny**
213+
faster than findFirst on parallel streams
214+
215+
### Primitive-Type Streams
216+
217+
Wrappers (like Stream<Integer>) are inefficients. It requires a lot of unboxing and boxing for each element. Better to use `IntStream`, `DoubleStream`, etc.
218+
219+
**Creation**
220+
221+
```java
222+
IntStream stream = IntStream.of(1, 2, 3, 5, 7);
223+
stream = IntStream.of(myArray); // from an array
224+
stream = IntStream.range(5, 80); // range from 5 to 80
225+
226+
Random gen = new Random();
227+
IntStream rand = gen(1, 9); // stream of randoms
228+
```
229+
230+
Use *mapToX* (mapToObj, mapToDouble, etc.) if the function yields Object, double, etc. values.
231+
232+
### Grouping Results
233+
234+
**Collectors.groupingBy**
235+
236+
```java
237+
// Groupe by length
238+
Map<Integer, List<String>> groups = stream
239+
.collect(Collectors.groupingBy(w -> w.length()));
240+
//> 4=[Bohr], 5=[Tesla], 6=[Darwin, Newton], ...
241+
```
242+
243+
**Collectors.toSet**
244+
245+
```java
246+
// Same as before but with Set
247+
... Collectors.groupingBy(
248+
w -> w.substring(0, 1), Collectors.toSet()) ...
249+
```
250+
251+
**Collectors.counting**
252+
Count the number of values in a group
253+
254+
**Collectors.summing__**
255+
`summingInt`, `summingLong`, `summingDouble` to sum group values
256+
257+
**Collectors.averaging__**
258+
`averagingInt`, `averagingLong`, ...
259+
260+
```java
261+
// Average length of each element of a group
262+
Collectors.averagingInt(String::length)
263+
```
264+
265+
*PS*: Don't forget Optional (like `Map<T, Optional<T>>`) with some Collection methods (like `Collectors.maxBy`).
266+
267+
### Parallel Streams
268+
269+
**Creation**
270+
271+
```java
272+
Stream<String> parStream = list.parallelStream();
273+
Stream<String> parStream = Stream.of(myArray).parallel();
274+
```
275+
276+
**unordered**
277+
Can speed up the `limit` or `distinct`
278+
279+
```java
280+
stream.parallelStream().unordered().distinct();
281+
```
282+
283+
284+
*PS*: Work with the streams library. Eg. use `filter(x -> x.length() < 9)` instead of a `forEach` with an `if`.
285+
286+
## Optional
287+
In Java, it is common to use null to denote absence of result.
288+
Problems when no checks: `NullPointerException`.
289+
290+
```java
291+
// Optional<String> contains a string or nothing
292+
Optional<String> res = stream
293+
.filter(w -> w.length() > 10)
294+
.findFirst();
295+
296+
// length of the value or "" if nothing
297+
int length = res.orElse("").length();
298+
299+
// run the lambda if there is a value
300+
res.ifPresent(v -> results.add(v));
301+
```
302+
303+
Return an Optional
304+
305+
```java
306+
Optional<Double> squareRoot(double x) {
307+
if (x >= 0) { return Optional.of(Math.sqrt(x)); }
308+
else { return Optional.empty(); }
309+
}
310+
```
311+
312+
-----
313+
314+
All examples with "list" use :
315+
316+
```
317+
List<String> list = [Bohr, Darwin, Galilei, Tesla, Einstein, Newton]
318+
```
319+
320+
321+
This cheat sheet was based on the lecture of Cay Horstmann
322+
http://horstmann.com/heig-vd/spring2015/poo/
323+
324+

0 commit comments

Comments
 (0)