preface

The Java 8 API has added a new abstraction called a Stream that lets you process data in a declarative way.


I. Stream characteristics

  1. A stream does not store data, but evaluates it according to specific rules, generally producing output.
  2. Stream does not change the data source, and typically produces a new collection or a value.
  3. Stream has a delayed execution property, where intermediate operations are executed only when terminal operations are called.

2. Stream instantiation

2.1 Through the Collection

 public static List<Employee> getEmployeeDataList(a){
    List<Employee> list = new ArrayList<>();
     list.add(new Employee(1."Zhang".20.8500D.1));
     list.add(new Employee(2."Bill".18.600D.1));
     list.add(new Employee(3."Fifty".21.5500D.3));
     list.add(new Employee(4."White".30.8500D.2));
     return list;
 }

public static void main(String[] args) {
    List<Employee> employees = getEmployeeDataList();
    // Return a sequential stream (retrieved in collection order)
    Stream<Employee> stream = employees.stream();
    // Return a parallel stream (similar to a thread to fetch data, unordered)
    Stream<Employee> parallelStream = employees.parallelStream();
}
Copy the code

2.2 Through arrays

public static void main(String[] args) {
    int[] arr = new int[] {1.2.3.4.5.6};
    IntStream intStream = Arrays.stream(arr);

    Employee e1 = new Employee(1."Zhang".20.8500D.1);
    Employee e2 = new Employee(2."Bill".18.600D.1);
    Employee[] employees = new Employee[]{e1,e2};
    Stream<Employee> stream = Arrays.stream(employees);
}
Copy the code

2.3 Through the of method of Stream

public static void main(String[] args) {
 Stream<Integer> integerStream = Stream.of(1.2.3.4.5.6);
}
Copy the code

2.4 Through infinite flow

public static void main(String[] args) {
    // Generate an even number
    Stream.iterate(0,t->t+2).limit(10).forEach(System.out::println);
    // 10 random numbers
    Stream.generate(Math::random).limit(10).forEach(System.out::println);
}
Copy the code

Stream API method

3.1 the filter

Select employees whose salary is greater than 8000:

public static void main(String[] args) {
    List<Employee> employees = getEmployeeDataList();
    Stream<Employee> stream = employees.stream();
    stream.filter(e -> e.getSalary() > 8000).forEach(t->{
        System.out.println("Employees earning more than $8,000 ->>>"+t);
    });
}
Copy the code

3.2 limit

Prints the number of collection elements

public static void main(String[] args) {
    List<Employee> employees = getEmployeeDataList();
    employees.stream().limit(3).forEach(t-> System.out.println("Output number of set elements ->>>"+t));
}
Copy the code

3.3 the skip

Filter out the first two elements

public static void main(String[] args) {
    List<Employee> employees = getEmployeeDataList();
    employees.stream().skip(2).forEach(t-> System.out.println("Filter out first 2 elements ->>>"+t));
}
Copy the code

3.4 the distinct

Set to heavy

public static void main(String[] args) {
    List<Employee> list = new ArrayList<>();
    list.add(new Employee(1."Zhang".20.8500D.1));
    list.add(new Employee(1."Zhang".20.8500D.1));
    list.add(new Employee(1."Zhang".20.8500D.1));
    list.add(new Employee(1."Zhang".20.8500D.1));
    list.add(new Employee(1."Zhang".20.8500D.1));
    list.stream().distinct().forEach(t-> System.out.println(->>>"+t));
}
Copy the code

3.5 the map

Case conversion

public static void main(String[] args) {
    List<String> list = Arrays.asList("a"."b"."c"."d");
    list.stream().map(str -> str.toUpperCase(Locale.ROOT)).forEach(t-> System.out.println("Case conversion ->>>"+t));
}
Copy the code

Gets the name of an employee whose name is greater than 3

public static void main(String[] args) {
    // Get the name of an employee whose name is greater than 3
    List<Employee> list = getEmployeeDataList();
    Stream<String> nameStream = list.stream().map(Employee::getName);
    nameStream.filter(name -> name.length() > 3).forEach(t-> System.out.println("Get employee whose name is greater than 3 ->>>"+t));
}
Copy the code

3.6 the sorting

First, sort by age from youngest to oldest. When they are the same age, sort by salary

public static void main(String[] args) {
   List<Employee> list = getEmployeeDataList();
   list.stream().sorted((e1,e2)->{
       int age = Integer.compare(e1.getAge(),e2.getAge());
       if(age ! =0) {return age;
       }else {
           return Double.compare(e1.getSalary(),e2.getSalary());
       }
   }).forEach(System.out::println);
}
Copy the code

3.7 Matching and Searching

1, allMatch

AllMatch: Checks whether all elements match

Determine if all employees are older than 18

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    boolean allMatch = list.stream().allMatch(e -> e.getAge() > 18);
    System.out.println(allMatch);
}
Copy the code
Return all satisfiedtrue, otherwise returnfalse
Copy the code

2, anyMatch

AnyMatch: Checks if at least one element is matched

Is there any employee whose salary is more than 8000

public static void main(String[] args) {
   List<Employee> list = getEmployeeDataList();
    boolean anyMatch = list.stream().anyMatch(employee -> employee.getSalary() > 8000);
    System.out.println(anyMatch);
}
Copy the code
Return if an element condition existstrue
Copy the code

3, noneMatch

NoneMatch: Checks if there are no matching elements

Check whether there is an employee surnamed Zhang

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    boolean noneMatch = list.stream().noneMatch(employee -> employee.getName().startsWith("Zhang"));
    System.out.println(noneMatch);
}
Copy the code
returnfalse, means yes, otherwise noCopy the code

4, findFirst

FindFirst: Returns the first element

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    Optional<Employee> first = list.stream().findFirst();
    System.out.println(first);
}
Copy the code

5, findAny

FindAny: Returns any element in the current stream

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    Optional<Employee> first = list.parallelStream().findAny();
    System.out.println(first);
}
Copy the code

6, the count

Count: Returns the total number of elements in the stream

Query the number of employees whose salary is greater than 8000

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    long count = list.stream().filter(employee -> employee.getSalary() > 8000).count();
    System.out.println(count);
}
Copy the code

7, Max

Max: Returns the maximum value in the stream

Query the highest employee salary

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    Stream<Double> doubleStream = list.stream().map(employee -> employee.getSalary());
    Optional<Double> max = doubleStream.max(Double::compare);
    System.out.println(max);
}
Copy the code

8 min.

Min: Returns the minimum value in the stream

Query the lowest employee salary

 public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    Optional<Employee> min = list.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
    System.out.println(min);
}
Copy the code

3.8 reduction

Reduce: You can combine elements in a stream repeatedly to get a value

Take the sum from 1 to 10

public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1.2.3.4.5.6.7.8.9.10);
    Integer reduce = list.stream().reduce(0, Integer::sum);
    System.out.println(reduce);
}
Copy the code
The first parameter of reduce0: indicates the initial value.Copy the code

Calculate the sum of all employees in the company

public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    // Get the salary
    Stream<Double> doubleStream = list.stream().map(Employee::getSalary);
    Optional<Double> reduce = doubleStream.reduce(Double::sum);
    System.out.println(reduce);
}
Copy the code

3.9 collect collect

Find an employee whose salary is greater than 8000 and return a list or set

 public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    List<Employee> collect = list.stream().filter(employee -> employee.getSalary() > 8000).collect(Collectors.toList());
    System.out.println(collect);
}
Copy the code
public static void main(String[] args) {
    List<Employee> list = getEmployeeDataList();
    Set<Employee> collect = list.stream().filter(employee -> employee.getSalary() > 8000).collect(Collectors.toSet());
    System.out.println(collect);
}
Copy the code

conclusion

We’ll continue to extend other interface implementations later in this article. If you can keep reading this, you’ll be rewarded for writing elegant streams with repeated practice.