如今Java14
已經(jīng)發(fā)布許久了,Java15
也在路上跑著了质涛,然鵝不少小伙伴Java8
的API
應該還沒用溜吧稠歉!今天跟各位小伙伴們聊聊Java Stream API
的具體使用方法以及應用場景。
舉哥簡單的例子汇陆,定義一個數(shù)組:
String[] users = new String[]{"張三","李四","王二"};
我們來使用之前的方式遍歷:
for(int i=0;i<users.length;i++){
System.out.println(users[i]);
}
亦或者使用:
for(String u:users){
System.out.println(u);
}
使用最新的API
實現(xiàn)方式:
Stream<String> stream = Stream.of(users);
stream.forEach(user-> System.out.println(user));
然鵝好像并沒有多么方便怒炸,僅僅少擼了一行代碼,下面跟大家分享一個稍微復雜一點的例子毡代。
首先定義一個學生類:
@Data
@Builder
public class Student {
private String name;
private Integer age;
private Integer sex;
private Double score;
}
定義基礎數(shù)據(jù):
List<Student> list = new ArrayList<>();
list.add(new Student("張三",28,1,78.9));
list.add(new Student("李四",20,1,98.0));
list.add(new Student("王二",29,0,100.0));
list.add(new Student("張三",28,1,78.5));
Stream<Student> stream = list.stream();
遍歷:
stream.forEach(stu-> System.out.println(stu.getName()));
過濾性別:
stream.filter(stu -> stu.getSex()==1)
.forEach(stu -> System.out.println(stu.getName()));
名字去重:
stream.distinct().forEach(stu -> System.out.println(stu.getName()));
年齡排序:
stream.sorted(Comparator.comparingInt(Student::getAge))
.forEach(stu -> System.out.println(stu.getName()));
排序反轉:
stream.sorted(Comparator.comparingInt(Student::getAge).reversed())
.forEach(stu -> System.out.println(stu.getName()));
姓名集合:
List<String> userList = stream.map(stu -> stu.getName())
.collect(Collectors.toList());
分數(shù)求和:
Optional<Double> totalScore = stream.map(Student::getScore)
.reduce((x, y) -> x+y);
System.out.println(totalScore.get());
求分數(shù)最大值:
Optional<Double> maxScore = stream.map(Student::getScore).reduce(Double::max);
求分數(shù)最小值:
Optional<Double> minScore = stream.map(Student::getScore).reduce(Double::min);
取前三名同學:
stream.sorted(Comparator.comparingDouble(Student::getScore).reversed())
.limit(3)
.forEach(System.out::println);
扔了前三名同學:
stream.sorted(Comparator.comparingDouble(Student::getScore).reversed())
.skip(3)
.forEach(System.out::println);
臥槽太多了阅羹,擼主舉不過來了,但是基本上常用的就這么幾個教寂。函數(shù)式編程寫出的代碼更加簡潔且意圖明確捏鱼,使用stream
接口讓你從此告別for
循環(huán),小伙伴們趕緊入坑享受吧@腋5及稹!