Stream 主要分为三部分 1. 创建流 2.中间操作 3.终止操作
Stream stringStream = list.stream();
无限流
迭代
Stream.iterate(0, (x) -> x+2 )
.forEach(System.out::println);
生成
Stream.generate(()-> Math.random())
.forEach(System.out::println);
多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何处理。而在终止操作是一次性全部处理,称为“惰性求值”
List students = Arrays.asList(
new Student("张三",18,88),
new Student("李四",18,80),
new Student("王五",19,60),
new Student("王五",19,60),
new Student("王五",19,60),
new Student("赵六",17,100)
);
// 1.过滤
@Test
public void test(){
//中间操作
Stream studentStream = students.stream()
.filter(s -> s.getAge() > 17);
//终止操作
studentStream.forEach(System.out::println);
}
//2.limit(n) :前几个
@Test
public void test2(){
students.stream()
.filter(s-> s.getScore()>70)
.limit(2)
.forEach(System.out::println);
}
//3. skip(n) 跳过前n个
@Test
public void test3(){
students.stream()
.filter(s->s.getAge()>17)
.skip(1) //跳过
.forEach(System.out::println);
}
// 4. distinct() 去重
@Test
public void test4(){
students.stream()
.filter(s->s.getAge()>17)
.skip(1) //跳过
.distinct() //去重,需要对象重写hashCode() equals() 两个方法
.forEach(System.out::println);
}
public static Stream<Character> getCharacterStream(String str){
List<Character> characters = new ArrayList<>();
for (Character c: str.toCharArray()) {
characters.add(c);
}
return characters.stream();
}
@Test
public void testMap(){
List<String> list = Arrays.asList("aaa","bbb","ccc");
Stream<Stream<Character>> chStream = list.stream()
.map(s-> getCharacterStream(s));
chStream.forEach(stream -> {
stream.forEach(System.out::println);
});
System.out.println("--------------------------------");
}
@Test
public void testFlatMap(){
List<String> list = Arrays.asList("aaa","bbb","ccc");
Stream<Character> flatStream = list.stream()
.flatMap(s-> getCharacterStream(s));
flatStream.forEach(System.out::println);
}
总结:
- map返回一个流,或者多个流的集合
- flatMap 是每个元素都合并到一个流中,最终产生一个流
/*
默认排序
*/
@Test
public void testSorted(){
List<String> list = Arrays.asList("aaa","BBB","AAA","aaa","ccc","CCC");
list.stream()
.sorted()
.forEach(System.out::println);
}
//数据
List<Student> students = Arrays.asList(
new Student("张三",18,88),
new Student("李四",18,80),
new Student("王五",19,60),
new Student("王五",19,60),
new Student("王五",19,60),
new Student("赵六",17,100)
);
//自定义排序
@Test
public void testSorted2(){
//先转换(List->List),然后排序
students.stream()
.map(Student::getAge)
.sorted(Comparator.comparingInt(s -> s))
.forEach(System.out::println);
//直接排序
students.stream()
.sorted((s1,s2)->{
if (s1.getAge() == s2.getAge()){
return Integer.compare(s1.getScore(),s2.getScore());
}else
return Integer.compare(s1.getAge(),s2.getAge());
})
.forEach(System.out::println);
}