程序員、java8、後端開發、碼農
java8
吐槽
程序員為了不天天996加班
學習java8流式語法提高開發效率
很多人吐槽性能低
你想想坐飛機多快,但為什麼做高鐵的人多了
這就是成本問題
目標
這裡不談底層原理,就把工作中實用的小demo輸出
- java8流式語法
- map
- filter
- Optional
- findFirst
- ::方法引用
- limit
- skip
上代碼案例
創建學生類和文具類,看json關係
每個學生有多套文具
List a=Lists.newArrayList(
new Stationery("鋼筆","紅本")
,new Stationery("鋼筆","本子"));
List b=Lists.newArrayList(
new Stationery("圓珠筆","綠本"));
List c=Lists.newArrayList(
new Stationery("鋼筆","藍子"),
new Stationery("鉛筆","黃本"));
初始化學生數據
List students=new ArrayList<>();
students.add(new Student(
"001","程序汪","男", a,18));
students.add(new Student(
"002","小紅","女", b,11));
students.add(new Student(
"003","小美","女", c,10));
Optional防空利器
說白了把if-else語法的壓扁了
//集合防空
Optional
.ofNullable(students)
.orElse(Collections.emptyList())
. forEach(System.out::println);
1
Optional+findFirst
集合中找一條數據
Optional oFindFirst=students.stream()
.filter(Objects::nonNull)
.map(Student::getName)
.filter(f->StringUtils.equals(f,"程序汪"))
.findFirst();
這樣判斷和if-else沒區別
if(oFindFirst.isPresent()){
System.out.println("給"+oFindFirst.get()+"發獎金啦");
}
那就來個簡潔的ifPresent
oFindFirst.ifPresent(f->{System.out.println("給"+f+"發獎金啦");});
1
filter過濾
students.stream()
.filter(Objects::nonNull)
.forEach(f->{
System.out.println(f.getName());
});
map
集合變形
List names=students.stream()
.filter(Objects::nonNull)
.map(Student::getName)
.collect(Collectors.toList());
names.forEach(System.out::println);
flatMap扁平化
和map的區別是,map是1對1的,flatMap是1對多
相等有集合list.add 和list.addAll區別
如下把學生集合中文具集合屬性,扁平化在輸出
對應複雜的集合嵌套類,處理起來非常爽
students.stream()
.filter(Objects::nonNull)
.map(Student::getStationerys)
.flatMap(List::stream)
.forEach(System.out::println);
list轉map
Map map=students.stream()
.filter(Objects::nonNull)
.collect(
Collectors
.toMap(Student::getStudentId,s->s));
System.out.println(JSON.toJSON(map));
輸出結果
1
list轉map分組
Map> map2=students
.stream()
.filter(Objects::nonNull)
.collect(Collectors.groupingBy(stu->stu.getSex()));
1
limit
當集合空是limit返回的是一個空集合不是null
這樣不容易NEP
List names2=students.stream()
.filter(Objects::nonNull)
.map(Student::getName)
.filter(f->StringUtils.equals(f,"aaa"))
.limit(1).collect(Collectors.toList());
names2.forEach(System.out::println);
skip
limit+skip類似mysql的limit關鍵字用法
List names33=students.stream()
.filter(Objects::nonNull)
.map(Student::getName)
.skip(2)
.limit(1).collect(Collectors.toList());
names33.forEach(System.out::println);
集合排序
那是相當簡潔
Collections.sort(students,
Comparator.comparing(Student::getAge));
students.forEach(System.out::println);
並行
不能亂用小心線程安全問題,後面有空單獨整理下這個並行的
students.parallelStream().forEach(System.out::println);