Java stream 的基本使用
package com. zhong. streamdemo. usestreamdemo ;
import jdk. jfr. DataAmount ;
import lombok. AllArgsConstructor ;
import lombok. Data ;
import lombok. NoArgsConstructor ;
import java. util. ArrayList ;
import java. util. Comparator ;
import java. util. List ;
import java. util. Objects ;
import java. util. stream. Stream ;
public class UseStream {
public static void main ( String [ ] args) {
System . out. println ( "-------------筛选成绩大于60分的信息-------------" ) ;
ArrayList < Double > strem1 = new ArrayList < > ( List . of ( 60.1 , 45.2 , 90.2 , 99.9 , 76.3 ) ) ;
List < Double > collect = strem1. stream ( )
. filter ( x -> x > 60 )
. toList ( ) ;
System . out. println ( collect) ;
System . out. println ( "-------------stream 对于对象的操作-------------" ) ;
ArrayList < Student > students = new ArrayList < > ( List . of (
new Student ( "小钟" , 22 , 179.1 ) ,
new Student ( "小钟" , 22 , 179.1 ) ,
new Student ( "小王" , 21 , 153.9 ) ,
new Student ( "小王" , 21 , 153.9 ) ,
new Student ( "张三" , 52 , 160.8 ) ,
new Student ( "李四" , 42 , 140.5 ) ,
new Student ( "王五" , 18 , 135.3 )
) ) ;
System . out. println ( "-------------筛选年龄大于 17 且小于 30 的学生信息-------------" ) ;
List < Student > list = students. stream ( )
. filter ( x -> x. getAge ( ) > 17 )
. filter ( x -> x. getAge ( ) < 30 )
. toList ( ) ;
list. forEach ( System . out:: println ) ;
System . out. println ( "-------------筛选身高前三的学生信息-------------" ) ;
List < Student > list1 = students. stream ( )
. sorted ( Comparator . comparing ( Student :: getHeight ) )
. skip ( students. size ( ) - 3 )
. toList ( ) ;
list1. forEach ( System . out:: println ) ;
System . out. println ( "-------------筛选身高前三的学生信息-------------" ) ;
List < Student > list2 = students. stream ( )
. sorted ( Comparator . comparing ( Student :: getHeight ) )
. limit ( 2 )
. toList ( ) ;
list2. forEach ( System . out:: println ) ;
System . out. println ( "-------------筛选身高超过 153 的学生的姓名 去除重复的名字-------------" ) ;
List < String > list3 = students. stream ( )
. filter ( x -> x. getHeight ( ) > 153 )
. map ( Student :: getName )
. distinct ( )
. toList ( ) ;
System . out. println ( list3) ;
System . out. println ( "-------------Stream.concat(stream1, stream2) 合并流-------------" ) ;
Stream < String > stream1 = Stream . of ( "张三1" , "李四1" ) ;
Stream < String > stream2 = Stream . of ( "张三2" , "李四2" , "王五2" ) ;
Stream < String > concatStream = Stream . concat ( stream1, stream2) ;
concatStream. forEach ( System . out:: println ) ;
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class Student {
private String name;
private int age;
private double height;
}