1. 什么是Stream?
是对集合collection对象的功能增强
并不是集合元素,他不是数据结构,像一个高级的Iterator
提供串行和并行两种模式进行汇聚操作
2. Stream流的创建
Collection.stream()单线程
Collection.parallelStream()多线程,效率高
Stream.of(1,2,3,4,5)
Arrays.stream(intArray)
BufferedReader in = new BufferedReader() in.lines()
Files.list(path)等等
3. Stream流的使用
sorted排序,limit取流数据的前几个数据
@Test public void test02() { List<Student> list = Lists.newArrayList( new Student("刘备", 18), new Student("关羽", 17), new Student("张飞", 16), new Student("赵云", 15), new Student("诸葛亮", 15), new Student("刘禅", 3)); //sorted排序(升序),limit取流数据的前几个数据 System.out.println(list.stream().sorted(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o1.getAge() - o2.getAge(); } }).limit(4).collect(Collectors.toList()).toString()); } [Student(name=刘禅, age=3), Student(name=赵云, age=15), Student(name=诸葛亮, age=15), Student(name=张飞, age=16)]
filter 过滤
@Test public void test03(){ List<Student> list = Lists.newArrayList( new Student("刘备", 18), new Student("关羽", 17), new Student("张飞", 16), new Student("赵云", 15), new Student("诸葛亮", 15), new Student("刘禅", 3)); System.out.println(list.stream().filter(new Predicate<Student>() { @Override public boolean test(Student student) { return student.getAge() >= 15 && student.getName().length() > 2; } }).sorted(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { return o2.getAge() - o1.getAge(); } }).collect(Collectors.toList()).toString()); } [Student(name=诸葛亮, age=15)]
map 元素转化 对象转字符串
@Test public void test04(){ List<Student> list = Lists.newArrayList( new Student("刘备", 18), new Student("关羽", 17), new Student("张飞", 16), new Student("赵云", 15), new Student("诸葛亮", 15), new Student("刘禅", 3)); System.out.println(list.stream().map(new Function<Student, Object>() { @Override public Object apply(Student student) { return student.getName(); } }).collect(Collectors.toList()).toString()); } [刘备, 关羽, 张飞, 赵云, 诸葛亮, 刘禅]
distinct 去重
peek 查看流里面的每个元素
skip 跳过前n个元素