Java8 Stream流式程式設計,極大解放你的生產力!
技術標籤:streamsmsopencllambdaproperty
java8自帶常用的函式式介面
Predicate<T> boolean test(T t)
傳入一個引數返回boolean值Consumer<T> void accept(T t)
傳入一個引數,無返回值Function<T,R> R apply(T t)
傳入一個引數,返回另一個型別
準備資料
//計算機俱樂部 privatestaticList<Student>computerClub=Arrays.asList( newStudent("2015134001","小明",15,"1501"), newStudent("2015134003","小王",14,"1503"), newStudent("2015134006","小張",15,"1501"), newStudent("2015134008","小樑",17,"1505") ); //籃球俱樂部 privatestaticList<Student>basketballClub=Arrays.asList( newStudent("2015134012","小c",13,"1503"), newStudent("2015134013","小s",14,"1503"), newStudent("2015134015","小d",15,"1504"), newStudent("2015134018","小y",16,"1505") ); //乒乓球俱樂部 privatestaticList<Student>pingpongClub=Arrays.asList( newStudent("2015134022","小u",16,"1502"), newStudent("2015134021","小i",14,"1502"), newStudent("2015134026","小m",17,"1504"), newStudent("2015134027","小n",16,"1504") ); privatestaticList<List<Student>>allClubStu=newArrayList<>(); allClubStu.add(computerClub); allClubStu.add(basketballClub); allClubStu.add(pingpongClub);
常用的stream三種建立方式
集合
Collection.stream()
靜態方法
Stream.of
陣列
Arrays.stream
//1.集合 Stream<Student>stream=basketballClub.stream(); //2.靜態方法 Stream<String>stream2=Stream.of("a","b","c"); //3.陣列 String[]arr={"a","b","c"}; Stream<String>stream3=Arrays.stream(arr);
Stream的終止操作
foreach(Consumer c)
遍歷操作collect(Collector)
將流轉化為其他形式max(Comparator)
返回流中最大值min(Comparator)
返回流中最小值count
返回流中元素綜述
Collectors 具體方法
toList List<T>
把流中元素收集到ListtoSet Set<T>
把流中元素收集到SettoCollection Coolection<T>
把流中元素收集到Collection中groupingBy Map<K,List<T>>
根據K屬性對流進行分組partitioningBy Map<boolean, List<T>>
根據boolean值進行分組
//此處只是演示此類需求直接用List構造器即可
List<Student>collect=computerClub.stream().collect(Collectors.toList());
Set<Student>collect1=pingpongClub.stream().collect(Collectors.toSet());
//注意key必須是唯一的如果不是唯一的會報錯而不是像普通map那樣覆蓋
Map<String,String>collect2=pingpongClub.stream()
.collect(Collectors.toMap(Student::getIdNum,Student::getName));
//分組類似於資料庫中的groupby
Map<String,List<Student>>collect3=pingpongClub.stream()
.collect(Collectors.groupingBy(Student::getClassNum));
//字串拼接第一個引數是分隔符第二個引數是字首第三個引數是字尾
Stringcollect4=pingpongClub.stream().map(Student::getName).collect(Collectors.joining(",","【","】"));
//【小u,小i,小m,小n】
//三個俱樂部符合年齡要求的按照班級分組
Map<String,List<Student>>collect5=Stream.of(basketballClub,pingpongClub,computerClub)
.flatMap(e->e.stream().filter(s->s.getAge()<17))
.collect(Collectors.groupingBy(Student::getClassNum));
//按照是否年齡>16進行分組key為true和false
ConcurrentMap<Boolean,List<Student>>collect6=Stream.of(basketballClub,pingpongClub,computerClub)
.flatMap(Collection::stream)
.collect(Collectors.groupingByConcurrent(s->s.getAge()>16));
Stream的中間操作
filter(Predicate)
篩選流中某些元素
//篩選1501班的學生
computerClub.stream().filter(e->e.getClassNum().equals("1501")).forEach(System.out::println);
//篩選年齡大於15的學生
List<Student>collect=computerClub.stream().filter(e->e.getAge()>15).collect(Collectors.toList());
map(Function f)
接收流中元素,並且將其對映成為新元素,例如從student物件中取name屬性
//籃球俱樂部所有成員名+暫時住上商標^_^,並且獲取所有隊員名
List<String>collect1=basketballClub.stream()
.map(e->e.getName()+"^_^")
.collect(Collectors.toList());
collect1.forEach(System.out::println);
//小c^_^^_^
//小s^_^^_^
//小d^_^^_^
//小y^_^^_^
flatMap(Function f)
將所有流中的元素併到一起連線成一個流
//獲取年齡大於15的所有俱樂部成員
List<Student>collect2=Stream.of(basketballClub,computerClub,pingpongClub)
.flatMap(e->e.stream().filter(s->s.getAge()>15))
.collect(Collectors.toList());
collect2.forEach(System.out::println);
//用雙層list獲取所有年齡大於15的俱樂部成員
List<Student>collect3=allClubStu.stream()
.flatMap(e->e.stream().filter(s->s.getAge()>15))
.collect(Collectors.toList());
collect3.forEach(System.out::println);
peek(Consumer c)
獲取流中元素,操作流中元素,與foreach不同的是不會截斷流,可繼續操作流
//籃球俱樂部所有成員名+贊助商商標^_^,並且獲取所有隊員詳細內容
List<Student>collect=basketballClub.stream()
.peek(e->e.setName(e.getName()+"^_^"))
.collect(Collectors.toList());
collect.forEach(System.out::println);
//Student{idNum='2015134012',name='小c^_^',age=13,classNum='1503'}
//Student{idNum='2015134013',name='小s^_^',age=14,classNum='1503'}
//Student{idNum='2015134015',name='小d^_^',age=15,classNum='1504'}
//Student{idNum='2015134018',name='小y^_^',age=16,classNum='1505'}
distinct()
通過流所生成元素的equals和hashCode去重limit(long val)
截斷流,取流中前val個元素sorted(Comparator)
產生一個新流,按照比較器規則排序sorted()
產生一個新流,按照自然順序排序
List<String>list=Arrays.asList("b","b","c","a");
list.forEach(System.out::print);//bbca
List<String>collect=list.stream().distinct().sorted().collect(Collectors.toList());
collect.forEach(System.out::print);//abc
//獲取list中排序後的top2即截斷取前兩個
List<String>collect1=list.stream().distinct().sorted().limit(2).collect(Collectors.toList());
collect1.forEach(System.out::print);//ab
匹配
booelan allMatch(Predicate)
都符合boolean anyMatch(Predicate)
任一元素符合boolean noneMatch(Predicate)
都不符合
booleanb=basketballClub.stream().allMatch(e->e.getAge()<20);
booleanb1=basketballClub.stream().anyMatch(e->e.getAge()<20);
booleanb2=basketballClub.stream().noneMatch(e->e.getAge()<20);
尋找元素
findFirst
——返回第一個元素findAny
——返回當前流中的任意元素
Optional<Student>first=basketballClub.stream().findFirst();
if(first.isPresent()){
Studentstudent=first.get();
System.out.println(student);
}
Optional<Student>any=basketballClub.stream().findAny();
if(any.isPresent()){
Studentstudent2=any.get();
System.out.println(student2);
}
Optional<Student>any1=basketballClub.stream().parallel().findAny();
System.out.println(any1);
計數和極值
count
——返回流中元素的總個數max
——返回流中最大值min
——返回流中最小值
longcount=basketballClub.stream().count();
Optional<Student>max=basketballClub.stream().max(Comparator.comparing(Student::getAge));
if(max.isPresent()){
Studentstudent=max.get();
}
Optional<Student>min=basketballClub.stream().min(Comparator.comparingInt(Student::getAge));
if(min.isPresent()){
Studentstudent=min.get();
}
END
推薦好文
強大,10k+點讚的 SpringBoot 後臺管理系統竟然出了詳細教程!
分享一套基於SpringBoot和Vue的企業級中後臺開源專案,程式碼很規範!
能掙錢的,開源 SpringBoot 商城系統,功能超全,超漂亮!