Skip to content

Commit 69ffebb

Browse files
committed
添加stream使用规范
1 parent 741068c commit 69ffebb

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# java中stream使用规范
2+
3+
## 1. stream中的filter表达式不要写得太长,对于复杂的表达式建议封装方法;
4+
5+
例如:
6+
7+
```java
8+
List<FlightOrder> orders = orders.stream()
9+
.filter(order -> StringUtils.equals(order.status, "Submitted")
10+
&& StringUtils.equals(order.paymentStatus, "Billed")
11+
&& StringUtils.equals(order.authorizeStatus, "Passed"))
12+
.collect(Collectors.toList();
13+
```
14+
15+
可以重构为
16+
17+
```java
18+
List<FlightOrder> orders = orders.stream()
19+
.filter(this::orderCanTicketing)
20+
.collect(Collectors.toList();
21+
```
22+
23+
## 2. 不要嵌套使用stream,嵌套的steam可读性很差,建议将内层的stream封装成独立的方法;
24+
25+
## 3. stream要适当地换行,不要写在一行中;
26+
27+
## 4. 不要在stream中访问数据库;
28+
29+
原因: 在循环中访问数据库往往导致性能问题。
30+
31+
## 5. 不要使用stream来更新数据,只用stream来查询
32+
33+
例如:
34+
35+
```java
36+
List<FlightOrder> orders = orders.stream()
37+
.filter(this::orderCanTicketing)
38+
.map(this::setTicketSuccess)
39+
.collect(Collectors.toList();
40+
41+
private FlightOrder setTicketSuccess(FlightOrder order) {
42+
order.setStatus("TicketSuccess");
43+
return order;
44+
}
45+
```
46+
47+
可以重构为
48+
49+
```java
50+
List<FlightOrder> orders = orders.stream()
51+
.filter(this::orderCanTicketing)
52+
.collect(Collectors.toList();
53+
54+
orders.foreach(this::setTicketSuccess);
55+
56+
private void setTicketSuccess(FlightOrder order) {
57+
//...
58+
}
59+
```

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy