Stream流
在Java 8中,得益于Lambda所带来的函数式编程,引入了一个全新的Stream概念,用于解决已有集合类库既有的弊端。
1.2 惰性求值与及早求值
惰性求值:只描述Stream,操作的结果也是Stream,这样的操作称为惰性求值。惰性求值可以像建造者模式一样链式使用,最后再使用及早求值得到最终结果。
及早求值:得到最终的结果而不是Stream,这样的操作称为及早求值。
2、常用的流
2.1 collect(Collectors.toList())
将流转换为list。还有toSet(),toMap()等。及早求值。
public class TestCase {
public static void main(String[] args) {
List<Student> studentList = Stream.of(new Student("路飞", 22, 175),
new Student("红发", 40, 180),
new Student("白胡子", 50, 185)).collect(Collectors.toList());
System.out.println(studentList);
}
}
//输出结果
//[Student{name='路飞', age=22, stature=175, specialities=null},
//Student{name='红发', age=40, stature=180, specialities=null},
//Student{name='白胡子', age=50, stature=185, specialities=null}]
2.2 filter
顾名思义,起过滤筛选的作用。内部就是Predicate接口。惰性求值。
