Java8 new features ------ Stream API and Optional Class

Stream API

1, Stream API understanding:

①, Stream concern is the operation of the data, dealing with the CPU. Collection concern is to store data, dealing with memory

②, java8 provides a api, api can use this filter, sort the data in the memory mapping, and other reduction operation. Related operations similar to sql database tables in.

2, Notes

①, Stream elements themselves are not stored

②, Stream does not change the source object. Instead, they will return the result of holding a new Stream

③, Stream delay operation is performed. This means they will need to wait until the results before execution

3, Stream flow of execution

①, Stream instantiation

②, an intermediate series of operations (filtering, mapping, ...)

③, terminating operation

4, Description:

An intermediate chain of operations, on the data source is processed

Upon termination of operations performed, the operation is executed intermediate chain, and produce results. After that, it will not be used

5, the operation of the intermediate Stream:

①, screening the slice
Here Insert Picture Description
code is as follows:

@Test
public void test4(){
    List<Employee> list = EmployeeData.getEmployees();
    Stream<Employee> stream = list.stream();
    //filter
    stream.filter(e ->e.getSalary() > 7000).forEach(System.out::println);
    //limit
    list.stream.limit(3).forEach(System.out::println);
    //limit
    list.stream.skip(3).forEach(System.out::println);
    //distinct
    list.stream.distinct().forEach(System.out::println);
}

②, the mapping
Here Insert Picture Description
code is as follows:

  @Test
    public void test4(){
        List<String> list = Arrays.asList("AA","BB","cc","dd");
        list.stream().map(str -> str.toLowerCase()).forEach(System.out::println);
        //获取员工姓名长度大于3的员工姓名
        List<Employee> employees = EmployeeData.getEmployees();
        //map和filter
        Stream<String> namesStream = employees.stream().map(Employee::getName);
        namesStream.filter(name -> name.length() > 3).forEach(System.out::println);

        //map
        Stream<Stream<Character>> streamStream = list.stream().map(ProxyTest::fromStringToStream);
        streamStream.forEach(s -> s.forEach(System.out::println));
        //flatMap
        Stream<Character> characterStream = list.stream().flatMap(ProxyTest::fromStringToStream);
        characterStream.forEach(System.out::println);
        
    }

    public static Stream<Character> fromStringToStream(String str){
        ArrayList<Character> list = new ArrayList<>();
        for (Character character : str.toCharArray()){
            list.add(character);
        }
        return  list.stream();
    }

③, sort
Here Insert Picture Description
code is as follows:

@Test
public void test7() {
    //sorted()-自然排序
    List<Integer> list = Arrays.asList(12, 43, 34, 87, -98, 7);
    list.stream().sorted().forEach(System.out::println);
    //sorted(Comployee com)-定制排序
    List<Employee> employees = EmployeeData.getEmployees();
    employees.stream().sorted((e1, e2) -> {
        int ageValue = Integer.compare(e1.getAge(), e2.getAge());
        if (ageValue != 0) {
            return ageValue;
        } else {
            return -Double.compare(e1.getSalary(), e2.getSalary());
        }
    }).forEach(System.out::println);
    
}

6, Stream termination operations:

①, and find matching
Here Insert Picture DescriptionHere Insert Picture Description
code is as follows:

@Test
public void test7() {
    List<Employee> employees = EmployeeData.getEmployees();
    //allMatch(predicate p)-检查是否匹配所有元素
    boolean allMatch = employees.stream().allMatch(e -> e.getAge() >18);
    //anyMatch(Predicate P)-检查是否至少匹配一个元素。
    boolean anyMatch = employees.stream().anyMatch(e ->e.getSalary() > 10000);
    //noneMatch(Predicate p)一 检查是否没有匹配的元素。
    boolean noneMatch = employees.stream().noneMatch(e -> e.getName().tartsWith("周"));
    ///findFirst- 返回第一 个元囊
    Optional<Employee> employee = employees.stream().findFirst();
    //findAny- -返回当前流中的任意元素
    optiona1<Employee> employee1 = employees.paralle1Stream().findAny();
    // count- 返回流 中元素的总个数
    long count = employees. stream().filter(e -> e.getSalary() > 5000).count();
    //max(Comparator c)一返回流中最大值
    Stream<Double> salaryStream = employees.stream().map(e -> e.getSalary());
    Optional<Double> maxsalary = salaryStream.max(Double :: compare);
    //min(Comparator c)-返回流 中最小值
    Optional<Employee> minsalary = employees.stream().min((e1,e2) -> Double.compare(e1.getSalary(), e2.getsalary()));
    //forEach(Consumer c)一内部迭代
    employees.stream().forEach(System.out :: print1n);
}

②, Reduction
Here Insert Picture Description
code is as follows:

@Test
public void test7() {
    //reduce(T identity, BinaryOperator)- 可以将流中元素反复结合起来,得到一个值。返回T
    //计算1-10的自然数的和
    List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
    Integer sum = list. stream().reduce( 0, Integer :: sum);//sun-->55
    //reduce(BinaryOperator)一可以将流中元素反复结合起来,得到一个值。返回optional<T>
    //计算公司所有员工工资的总和
    List<Employee> employees = EmployeeData.getEmployees();
    Stream<Double> salaryStream = emp1oyees.stream().map(Emp1oyee :: getSalary);
    Optional <Double> sumMoney = salaryStream. reduce(Double::sum);
}

③, collection
Here Insert Picture Description
code is as follows:

@Test
public void test7() {
    List<Employee> employees = Emp1oyeeData.getEmployees();
    List<Employee> employeelist = employees.stream().filter(e -> e.getSalary() > 8000).collect(Collectors.toList());
}

Optional Class

1, Introduction Optional class

      Optional class (java.util.Optional) is a container class, it can hold the value of type T, the representative value is present. Or just save null, it indicates that the value does not exist. Originally represented by a null value does not exist, now Optional can better express this concept. And avoid a null pointer exception.

2, Optional class object's method

  • Optional.of (T t): Create an instance Optional, t must be non-empty;
  • Optional.empty (): create an empty instance Optional
  • Optional.ofNullable (T t): t may be null

3, determines whether the object contained in the container Optional:

  • boolean isPresent (): determining whether an object comprising
  • void ifPresent (Consumer <? super T > consumer): If there is a value, Consumer executes
    code that implements the interface, and this value is passed to it as an argument.
  • Get Object Optional container:
  • T get (): If you call the object contains the value, return that value, otherwise Throws
  • T orElse (T other): If there is value will be returned, otherwise other object specified.
  • T orElseGet (Supplier other <extends T?>):: If there is value will be returned, otherwise the

4, Supplier interface object provides

  • T orElseThrow (Supplier exceptionSupplier <extends X ?>):: If there is a value then it is back to
    back, or thrown by the Supplier interface provides.

5, Optional use of Class

@Test
public void test7() {
    Girl girl = new Gir1();
    girl = nu11;
    //of(T t):保证t是非空的
    optional<Girl> optiona1Girl = Optional.of(gir1);
    //ofNullable(T t): t可以为null
    optional<Girl> optiona1Girl1 = Optional.ofNullable(gir1);
}

@Test
public void test2() {
    Boy b = new Boy("张三");
    Optional<Girl> opt = Optional.ofNullable(b.getGrilFriend());
    // 如果有女朋友就返回他的女朋友,否则只能欣赏“嫦娥”了
    Girl girl = opt.orElse(new Girl("嫦娥"));
    System.out.println("他的女朋友是:" + girl.getName());
Published 67 original articles · won praise 19 · views 9867

Guess you like

Origin blog.csdn.net/qq_41530004/article/details/104423252