File tree Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Expand file tree Collapse file tree 2 files changed +72
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .collection ;
2+
3+ import org .apache .commons .lang .StringUtils ;
4+
5+ import java .util .*;
6+
7+ /**
8+ * @Author: EnjoyCoding
9+ * @Date: 2020\3\14 0014 22:35
10+ * @Description:
11+ */
12+ public class ForeachTest {
13+ /**
14+ * 注意,使用foreach遍历的时候,也要进行判空操作,规避空指针
15+ *
16+ */
17+ public void foreachNPE () {
18+ String str =null ;
19+ List <String > list = Arrays .asList ("abc" , "def" , str );
20+ //foreach不判空,也会报空指针
21+ for (String letter : list ) {
22+ System .out .println (letter .length ());
23+ }
24+ }
25+
26+ public void removeElement () {
27+ //如果采用Arrays.asList(),是不能对集合进行增删操作的。
28+ List <String > list = new ArrayList <>();
29+ list .add ("1" );
30+ list .add ("2" );
31+ //想要遍历集合,删除元素,必须使用Iterator()。如果使用foreach(),会报错。
32+ //removeIf(),内部使用的就是Iterator()。
33+ list .removeIf (Objects ::isNull );
34+ }
35+
36+
37+ /**
38+ * java8中提供了非常方便的过滤以及遍历的操作。
39+ *
40+ */
41+ public void foreachJave8 () {
42+ String str =null ;
43+ List <String > list = Arrays .asList ("abc" , "def" , str );
44+ list .stream ().filter (StringUtils ::isNotEmpty ).forEach (System .out ::println );
45+ }
46+
47+ }
Original file line number Diff line number Diff line change 1+ package com .java8 .lambda ;
2+
3+ import com .bean .Worker ;
4+
5+ import java .util .ArrayList ;
6+ import java .util .List ;
7+ import java .util .Objects ;
8+
9+ /**
10+ * @Author: EnjoyCoding
11+ * @Date: 2020\3\14 0014 23:45
12+ * @Description:
13+ */
14+ public class LambdaDemo {
15+
16+ public void lambdaNonNull () {
17+ List <Worker > workerList = new ArrayList <>();
18+ Worker worker = new Worker ("123" , 18 , "lin" );
19+ workerList .add (worker );
20+ workerList .add (null );
21+ //过滤掉为空的对象,然后遍历
22+ // workerList.stream().filter(x->x!=null).forEach(System.out::println);
23+ workerList .stream ().filter (Objects ::nonNull ).forEach (System .out ::println );
24+ }
25+ }
You can’t perform that action at this time.
0 commit comments