-
过滤、截断、跳过、去重
代码中都有注释@Test public void test() { Student[] students = new Student[] { new Student("a", 1), new Student("b", 2), new Student("c", 3), new Student("d", 4), new Student("e", 5) }; // Stream流中间操作---过滤 Arrays.asList(students).stream().filter(s -> s.getAge() > 3).forEach(System.out::println); System.out.println("*********************************"); // Stream流中间操作---截断(取前几个数据) Arrays.asList(students).stream().limit(3).forEach(System.out::println); System.out.println("*********************************"); // Stream流中间操作---跳过(跳过前面几个数据) Arrays.asList(students).stream().skip(3).forEach(System.out::println); System.out.println("*********************************"); // Stream流中间操作---去重(根据equal和hashcode判断) Arrays.asList(students).stream().distinct().forEach(System.out::println); }
这些都是常规操作比较容易理解
-
映射map和flatMap
推荐我的另一篇博客
Stream流中间操作之map和flatMap的区别 -
排序
@Test public void test3(){ Student[] students = new Student[] { new Student("a.a", 1), new Student("b.b", 2), new Student("c.c", 3), new Student("d.d", 4), new Student("e.e", 5) }; // 报错,Student类没有默认的排序方法(没有实现Comparable接口) //Arrays.asList(students).stream().sorted().forEach(System.out::println); System.out.println("*********************************"); // Integer实现了Comparable接口,有默认排序方法 Arrays.asList(students).stream().map(Student::getAge).sorted().forEach(System.out::println); System.out.println("*********************************"); // 自定义比较器,传入一个Comparator的函数式接口 Arrays.asList(students).stream().sorted((x,y)->Integer.compare(x.getAge(),y.getAge())).forEach(System.out::println); // 推荐写法,效果跟上面的还是一样的 Arrays.asList(students).stream().sorted(Comparator.comparing(Student::getAge)).forEach(System.out::println); }
sort()没有参数的排序方法,会采取当前类的默认排序方法(需要该类实现Comparable接口,不然报错)
sorted(Comparator<? super T> comparator),传入一个Comparator的函数式接口,来自定义排序
Stream流中间操作举例
最新推荐文章于 2024-07-06 11:37:29 发布