Skip to content

Commit dba6138

Browse files
author
haizhu
committed
add chinese
1 parent f6fa2c0 commit dba6138

File tree

1 file changed

+359
-0
lines changed

1 file changed

+359
-0
lines changed

README_CN.md

Lines changed: 359 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,359 @@
1+
2+
# JAVA 8 - 备忘录
3+
4+
## Lambda 表达式
5+
```java
6+
(int a) -> a * 2; // 求a乘以2后的值
7+
a -> a * 2; // 或者更直接的去掉类型也是可以的
8+
```
9+
```java
10+
(a, b) -> a + b; // 相加
11+
```
12+
13+
如果lambda里面的代码块超过1行,可以配合使用 `{ }``return`来处理
14+
15+
```java
16+
(x, y) -> {
17+
int sum = x + y;
18+
int avg = sum / 2;
19+
return avg;
20+
}
21+
```
22+
23+
一个lamdba表达式必须依赖一个具体的功能接口而存在
24+
25+
```java
26+
interface MyMath {
27+
int getDoubleOf(int a);
28+
}
29+
30+
MyMath d = a -> a * 2; // 关联到具体的接口实现
31+
d.getDoubleOf(4); // is 8
32+
```
33+
34+
---
35+
36+
下面所有的测试都是用到这个`list` :
37+
38+
```java
39+
List<String> list = [Bohr, Darwin, Galilei, Tesla, Einstein, Newton]
40+
```
41+
42+
43+
## Collections 集合
44+
45+
**sort** `sort(list, comparator)`
46+
47+
```java
48+
list.sort((a, b) -> a.length() - b.length())
49+
list.sort(Comparator.comparing(n -> n.length())); // 使用具体Comparator接口实现
50+
list.sort(Comparator.comparing(String::length)); // 这样写和上面也是一样的
51+
//> [Bohr, Tesla, Darwin, Newton, Galilei, Einstein]
52+
```
53+
54+
**removeIf**
55+
56+
```java
57+
list.removeIf(w -> w.length() < 6);
58+
//> [Darwin, Galilei, Einstein, Newton]
59+
```
60+
61+
**merge**
62+
`merge(key, value, remappingFunction)`
63+
64+
```java
65+
Map<String, String> names = new HashMap<>();
66+
names.put("Albert", "Ein?");
67+
names.put("Marie", "Curie");
68+
names.put("Max", "Plank");
69+
70+
// "Albert" 这个值是存在的 就命中了后面处理流程
71+
// {Marie=Curie, Max=Plank, Albert=Einstein}
72+
names.merge("Albert", "stein", (old, val) -> old.substring(0, 3) + val);
73+
74+
// "Newname" 这个值是不存在的 所以后面的流程就不处理
75+
// {Marie=Curie, Newname=stein, Max=Plank, Albert=Einstein}
76+
names.merge("Newname", "stein", (old, val) -> old.substring(0, 3) + val);
77+
```
78+
79+
80+
## 方法引用 `Class::staticMethod`
81+
82+
允许引用类方法或者构造函数,引用时候是不执行的
83+
84+
```java
85+
//通过lamdba
86+
getPrimes(numbers, a -> StaticMethod.isPrime(a));
87+
88+
//通过应用方法:
89+
getPrimes(numbers, StaticMethod::isPrime);
90+
```
91+
92+
| Method Reference | Lambda Form |
93+
| ---------------- | ----------- |
94+
| `StaticMethod::isPrime` | `n -> StaticMethod.isPrime(n)` |
95+
| `String::toUpperCase` | `(String w) -> w.toUpperCase()` |
96+
| `String::compareTo` | `(String s, String t) -> s.compareTo(t)` |
97+
| `System.out::println` | `x -> System.out.println(x)` |
98+
| `Double::new` | `n -> new Double(n)` |
99+
| `String[]::new` | `(int n) -> new String[n]` |
100+
101+
102+
## Streams 流式处理
103+
104+
`collections`类似, 但有所不同
105+
106+
- 不能储存数据
107+
- 数据来源外部例如 (collection, file, db, web, ...)
108+
- `immutable`不可变性,不影响外部数据 (因为产生了一个新的stream)
109+
- `lazy`懒式处理 (只有在计算的时候才用到,不处理不用 !)
110+
111+
```java
112+
// 仅仅计算前3个"filter"
113+
Stream<String> longNames = list
114+
.filter(n -> n.length() > 8)
115+
.limit(3);
116+
```
117+
118+
**创建一个stream**
119+
120+
```java
121+
Stream<Integer> stream = Stream.of(1, 2, 3, 5, 7, 11);
122+
Stream<String> stream = Stream.of("Jazz", "Blues", "Rock");
123+
Stream<String> stream = Stream.of(myArray); // 通过数组
124+
list.stream(); // 通过list
125+
126+
// Infinit stream [0; inf[
127+
Stream<Integer> integers = Stream.iterate(0, n -> n + 1);
128+
```
129+
130+
**集合结果集**
131+
132+
```java
133+
//返回成一个数组 (::new 是构造函数的引用)
134+
String[] myArray = stream.toArray(String[]::new);
135+
136+
// 返回成list或set
137+
List<String> myList = stream.collect(Collectors.toList());
138+
Set<String> mySet = stream.collect(Collectors.toSet());
139+
140+
// 返回成String
141+
String str = list.collect(Collectors.joining(", "));
142+
143+
//返回成一个LinkedHashMap
144+
list.stream().collect(Collectors.toMap(k -> k, v -> v, (a, b) -> a, LinkedHashMap::new));
145+
//默认转换成HashMap
146+
list.stream().collect(Collectors.toMap(k -> k, v -> v));
147+
```
148+
149+
**map** `map(mapper)`<br>
150+
对每个元素进行类型转换
151+
152+
```java
153+
// 对每个元素使用 "toLowerCase" 处理
154+
res = stream.map(w -> w.toLowerCase());
155+
res = stream.map(String::toLowerCase);
156+
//> bohr darwin galilei tesla einstein newton
157+
158+
res = Stream.of(1,2,3,4,5).map(x -> x + 1);
159+
//> 2 3 4 5 6
160+
```
161+
162+
**filter** `filter(predicate)`<br>
163+
过滤处理,只保留匹配到的元素
164+
165+
```java
166+
// 过掉保留 "E" 开头的元素
167+
res = stream.filter(n -> n.substring(0, 1).equals("E"));
168+
//> Einstein
169+
170+
res = Stream.of(1,2,3,4,5).filter(x -> x < 3);
171+
//> 1 2
172+
```
173+
174+
**reduce**<br>
175+
汇聚处理成为单一返回结果
176+
177+
```java
178+
String reduced = stream
179+
.reduce("", (acc, el) -> acc + "|" + el);
180+
//> |Bohr|Darwin|Galilei|Tesla|Einstein|Newton
181+
```
182+
183+
**limit** `limit(maxSize)`
184+
保留前`maxSize`个元素
185+
186+
```java
187+
res = stream.limit(3);
188+
//> Bohr Darwin Galilei
189+
```
190+
191+
**skip**
192+
忽略掉前`n`个元素
193+
194+
```java
195+
res = strem.skip(2); // 忽略 Bohr 和 Darwin
196+
//> Galilei Tesla Einstein Newton
197+
```
198+
199+
**distinct**
200+
去重
201+
202+
```java
203+
res = Stream.of(1,0,0,1,0,1).distinct();
204+
//> 1 0
205+
```
206+
207+
**sorted**
208+
排序 (必须使用 *Comparable* 接口)
209+
210+
```java
211+
res = stream.sorted();
212+
//> Bohr Darwin Einstein Galilei Newton Tesla
213+
```
214+
215+
**allMatch**
216+
全匹配
217+
```java
218+
// 检查是否每个元素都是“e”开头
219+
boolean res = words.allMatch(n -> n.contains("e"));
220+
```
221+
222+
`anyMatch`: 只要其中一个元素包含"e"即可 <br>
223+
`noneMatch`: 元素里面是否没有"e"
224+
225+
**parallel**
226+
返回一个并行的stream
227+
228+
**findAny**
229+
在并行流上findFirst执行更快
230+
231+
### 原始类型的 Streams
232+
233+
原子类型的stream自动封装是低效的 (例如 Stream<Integer>) ,因为它需要对每个元素进行大量拆箱和装箱. 所以最好使用 `IntStream`, `DoubleStream`, 等等.
234+
235+
**初始化**
236+
237+
```java
238+
IntStream stream = IntStream.of(1, 2, 3, 5, 7);
239+
stream = IntStream.of(myArray); // 通过数组
240+
stream = IntStream.range(5, 80); // 5 到 80范围
241+
242+
Random gen = new Random();
243+
IntStream rand = gen(1, 9); // stream of randoms
244+
```
245+
246+
使用 *mapToX* (mapToObj, mapToDouble, mapToLong) 如果需要把字段转换成 Object, double, long的话. values.
247+
248+
### Grouping 数据集
249+
250+
**Collectors.groupingBy**
251+
252+
```java
253+
// 通过长度分组
254+
Map<Integer, List<String>> groups = stream
255+
.collect(Collectors.groupingBy(w -> w.length()));
256+
//> 4=[Bohr], 5=[Tesla], 6=[Darwin, Newton], ...
257+
```
258+
259+
**Collectors.toSet**
260+
261+
```java
262+
// 和之前一样但是使用的是Set
263+
... Collectors.groupingBy(
264+
w -> w.substring(0, 1), Collectors.toSet()) ...
265+
```
266+
267+
**Collectors.counting**
268+
获取元素总算
269+
270+
**Collectors.summing__**
271+
`summingInt`, `summingLong`, `summingDouble` 计算所有元素值相加后结果
272+
273+
**Collectors.averaging__**
274+
`averagingInt`, `averagingLong`, ...
275+
276+
```java
277+
// 计算平均数
278+
Collectors.averagingInt(String::length)
279+
```
280+
281+
*PS*: 另外不要忘记 Optional (例如 `Map<T, Optional<T>>`) 有同样的处理方法 (例如 `Collectors.maxBy`).
282+
283+
284+
### 并行 Streams
285+
286+
**创建一个并行处理的stream**
287+
288+
```java
289+
Stream<String> parStream = list.parallelStream();
290+
Stream<String> parStream = Stream.of(myArray).parallel();
291+
```
292+
293+
**unordered**
294+
能提高计算 `limit`,`distinct`的速度
295+
296+
```java
297+
stream.parallelStream().unordered().distinct();
298+
```
299+
300+
*PS*: 使用streams类库, 例如使用 `filter(x -> x.length() < 9)` 代替 `forEach` 和 `if`
301+
302+
303+
## Optional
304+
Java, 通常使用`null`表示没有结果,但是如果不检查的话很容易出现`NullPointerException`.
305+
306+
```java
307+
// Optional<String> 包含一个string和空
308+
Optional<String> res = stream
309+
.filter(w -> w.length() > 10)
310+
.findFirst();
311+
312+
// 返回元素长度或者返回 "" 如果没有的话
313+
int length = res.orElse("").length();
314+
315+
// 使用lambda作为一个返回值
316+
res.ifPresent(v -> results.add(v));
317+
```
318+
319+
返回一个 Optional
320+
321+
```java
322+
Optional<Double> squareRoot(double x) {
323+
if (x >= 0) { return Optional.of(Math.sqrt(x)); }
324+
else { return Optional.empty(); }
325+
}
326+
```
327+
328+
---
329+
330+
**注意引用推测限制**
331+
332+
```java
333+
interface Pair<A, B> {
334+
A first();
335+
B second();
336+
}
337+
```
338+
339+
一个 steam 类型 `Stream<Pair<String, Long>>` :
340+
341+
- `stream.sorted(Comparator.comparing(Pair::first)) // 有效`
342+
- `stream.sorted(Comparator.comparing(Pair::first).thenComparing(Pair::second)) // 无效`
343+
344+
Java不能通过 `.comparing(Pair::first)`回调过来的数据来判断类型, 故 `Pair::first` 就不能这样用了
345+
346+
如果需要使用泛型接口的话需要显示写清楚,否则无效
347+
348+
```java
349+
stream.sorted(
350+
Comparator.<Pair<String, Long>, String>comparing(Pair::first)
351+
.thenComparing(Pair::second)
352+
) // 有效
353+
```
354+
355+
---
356+
357+
This cheat sheet was based on the lecture of Cay Horstmann
358+
http://horstmann.com/heig-vd/spring2015/poo/
359+

0 commit comments

Comments
 (0)