您当前的位置: 首页 > 

Dongguo丶

暂无认证

  • 2浏览

    0关注

    472博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Stream API

Dongguo丶 发布时间:2018-08-05 18:28:44 ,浏览量:2

Java8中有两大最为重要的改变。第一个是 Lambda 表达式;另外一 个则是 Stream API(java.util.stream.*)。Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

流(Stream) 到底是什么呢?

是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。“集合讲的是数据,流讲的是计算!”

注意: ①Stream 自己不会存储元素。 ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。 ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

Stream 的操作三个步骤

        1、创建 Stream 一个数据源(如:集合、数组),获取一个流

2、 中间操作 一个中间操作链,对数据源的数据进行处理

3、终止操作(终端操作) 一个终止操作,执行中间操作链,并产生结果

一、创建 Stream

准备工作

package com.dongguo.java8.stream;

import java.util.Objects;

/**
 * @author Dongguo
 * @date 2021/8/14 0014-15:00
 * @description:
 */
public class Employee {

    private String name;
    private int age;
    private long salary;
    private Status Status;

    public Employee() {
    }

    public Employee(String name, int age, long salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    public Employee(String name, int age, long salary, Status status) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.Status = status;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public long getSalary() {
        return salary;
    }

    public void setSalary(long salary) {
        this.salary = salary;
    }

    public Status getStatus() {
        return Status;
    }

    public void setStatus(Status status) {
        this.Status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age && salary == employee.salary && Objects.equals(name, employee.name) && Status == employee.Status;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, salary, Status);
    }

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", status='" + Status + '\'' +
                '}';
    }
}
public  enum Status{
    FREE,
    BUSY,
    VOCATION
}

1、Java8 中的 Collection 接口被扩展,提供了 两个获取流的方法:  default Stream stream() : 返回一个顺序流

 default Stream parallelStream() : 返回一个并行流

2、由数组创建流 Java8 中的 Arrays 的静态方法 stream() 可 以获取数组流:  static Stream stream(T[] array): 返回一个流 重载形式,能够处理对应基本类型的数组:

 public static IntStream stream(int[] array)

 public static LongStream stream(long[] array)

 public static DoubleStream stream(double[] array)

3、由值创建流 可以使用静态方法 Stream.of(), 通过显示值 创建一个流。它可以接收任意数量的参数。  public static Stream of(T... values) : 返回一个流

4、由函数创建流:创建无限流 可以使用静态方法 Stream.iterate() 和 Stream.generate(), 创建无限流。

 5迭代 public static Stream iterate(final T seed, final  UnaryOperator f) 

 6生成 public static Stream generate(Supplier s) : 

/**
 * @author Dongguo
 * @date 2021/8/15 0015 8:16
 * @description:创建stream
 */
@Test
public void test1() {
    //1可以通过collection系列集合提供的stream()或parallelStream()
    List list = new ArrayList();
    Stream stream1 = list.stream();
    //2通过Arrays中的静态方法stream()
    Employee[] employees = new Employee[10];
    Stream stream2 = Arrays.stream(employees);
    //3通过Stream类中的静态方法of()
    Stream stream3 = Stream.of("aaa", "bbb");
    //4创建无限流
    Stream stream4 = Stream.iterate(0, (x) -> x + 2);
    //迭代
    stream4.limit(10)
            .forEach(System.out::println);

    //生成
    Stream.generate(()->Math.random())
            .limit(5)
            .forEach(System.out::println);
}
二、Stream 的中间操作  

多个中间操作可以连接起来形成一个流水线,除非流水 线上触发终止操作,否则中间操作不会执行任何的处理! 而在终止操作时一次性全部处理,称为“惰性求值”。

1、筛选与切片

 

filter

List employees = Arrays.asList(
    new Employee("张三", 18, 3000, Status.VOCATION),
    new Employee("张三", 18, 4000, Status.BUSY),
    new Employee("李四", 28, 5000, Status.FREE),
    new Employee("王五", 38, 6000, Status.FREE),
    new Employee("赵六", 48, 5500, Status.BUSY),
    new Employee("田七", 58, 4500, Status.VOCATION));
@Test
public void test() {
    //中间操作:不执行任何操作
    Stream stream1 = employees.stream()
            .filter((x) -> x.getAge() > 35);
    //终止操作:执行全部操作  惰性求值
    stream1.forEach(System.out::println);
}

limit

@Test
void test2() {
    employees.stream()
            .filter((x)->x.getSalary()>4000)
            .limit(2)
            .forEach(System.out::println);
}

skip

@Test
void test3() {
    employees.stream()
            .filter((x)->x.getSalary()>4000)
            .skip(2)
            .forEach(System.out::println);
}

 

distinct

需要重写hashcode和equals方法才能去重

List employees = Arrays.asList(
        new Employee("张三", 18, 3000, Status.VOCATION),
        new Employee("张三", 18, 4000, Status.BUSY),
        new Employee("李四", 28, 5000, Status.FREE),
        new Employee("王五", 38, 6000, Status.FREE),
        new Employee("王五", 38, 6000, Status.FREE),
        new Employee("赵六", 48, 5500, Status.BUSY),
        new Employee("田七", 58, 4500, Status.VOCATION));

@Test
public void test7() {
    employees.stream()
            .filter(e -> e.getSalary() > 3000)
            .distinct()
            .forEach(System.out::println);
}
运行结果
Employee{name='张三', age=18, salary=4000, status='BUSY'}
Employee{name='李四', age=28, salary=5000, status='FREE'}
Employee{name='王五', age=38, salary=6000, status='FREE'}
Employee{name='赵六', age=48, salary=5500, status='BUSY'}
Employee{name='田七', age=58, salary=4500, status='VOCATION'}

2.映射

map 

@Test
public void test4() {
    List list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
    //实现将字符串转大写
    list.stream()
            .map((x)->x.toUpperCase())
            .forEach(System.out::println);
    System.out.println("--------------");
    //提取所有Employee的名字
    employees.stream()
            .map(Employee::getName)
            .forEach(System.out::println);
}

flatMap

@Test
public void test5() {
    List list = Arrays.asList("aaa", "bbb", "ccc", "ddd");
    Stream stream1 = list.stream()
            .map(TestStream2::filterCharactor);
    stream1.forEach((s)->{
        s.forEach(System.out::println);
    });
    System.out.println("-------------------------");
    list.stream()
            .flatMap(TestStream2::filterCharactor)
            .forEach(System.out::println);
}
//将字符串提取字符
public static Stream filterCharactor(String str) {
    List list = new ArrayList();
    for (Character c: str.toCharArray()) {
        list.add(c);
    }
    return list.stream();
}

 

3、

@Test
public void test6() {
    List list = Arrays.asList("ccc", "aaa", "ddd", "bbb");
    //自然排序
    list.stream()
            .sorted()
            .forEach(System.out::println);
    System.out.println("----------------------------");
    //定制排序
    employees.stream()
            .sorted((e1,e2)->{
                if (e1.getAge() == e2.getAge()){
                    return e1.getName().compareTo(e2.getName());
                }
                return Integer.compare(e1.getAge(),e2.getAge());
            })
            .forEach(System.out::println);
}
三、Stream 的终止操作

终端操作会从流的流水线生成结果。其结果可以是任何不是流的 值,例如:List、Integer,甚至是 void 。 1、查找与匹配

List employees = Arrays.asList(
        new Employee("张三", 18, 3000, Status.VOCATION),
        new Employee("张三", 18, 4000, Status.BUSY),
        new Employee("李四", 28, 5000, Status.FREE),
        new Employee("王五", 38, 6000, Status.FREE),
        new Employee("赵六", 48, 5500, Status.BUSY),
        new Employee("田七", 58, 4500, Status.VOCATION));
@Test
public void test1() {
    boolean match1 = employees.stream()
            .allMatch((e) -> e.getStatus().equals(Status.BUSY));
    System.out.println(match1);
    boolean match2 = employees.stream()
            .anyMatch((e) -> e.getStatus().equals(Status.BUSY));
    System.out.println(match2);
    boolean match3 = employees.stream()
            .noneMatch((e) -> e.getStatus().equals(Status.BUSY));
    System.out.println(match3);
}
@Test
public void test2() {
    Optional op = employees.stream()
            .sorted((e1, e2) -> -Long.compare(e1.getSalary(), e2.getSalary()))
            .findFirst();
    System.out.println(op.get());  
    Optional op2 = employees.stream()
            .filter((e)->e.getStatus().equals(Status.FREE))
            .findAny();
    System.out.println(op2.get());
}

 

@Test
public void test3() {
    long count = employees.stream()
            .count();
    System.out.println(count);
    Optional max = employees.stream()
            .max((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge()));
    System.out.println(max.get());
    Optional min = employees.stream()
            .map(Employee::getSalary)
            .min((e1, e2) -> Long.compare(e1,e2));
    System.out.println(min.get());
}

2、归约

@Test
public void test4() {
    Listlist = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    Integer reduce = list.stream()
            .reduce(0, (x, y) -> x + y);
    System.out.println(reduce);

    System.out.println("---------------------");
    Optional op = employees.stream()
            .map(Employee::getSalary)
            .reduce(Long::sum);
    System.out.println(op.get());
}

3、收集

//1.
 R collect(Supplier supplier,
                  BiConsumer accumulator,
                  BiConsumer combiner);
//2.
 R collect(Collector            
关注
打赏
1638062488
查看更多评论
0.0506s