web123456

Use of stream in Java

Article Directory

  • 1. What is stream()
      • The main features of flow
  • 2. The steps to use stream
      • step:
  • 3. Common intermediate operations and terminal operations
      • Intermediate operation
      • Terminal operation
  • Four. Example

1. What is stream()

StreamThe API provides a high-level abstraction that allows us to convert sets into a streaming processing mode, allowing us to perform a series of operations in a large chain manner.

Simply put: it is to turn the collection into a stream, so that we can continuously perform the operations we want on this stream

The main features of flow

  1. No data stored: Streams will not change the original data structure, they only provide one inData Sourcemethod to perform an operation.

  2. Functional operations: The flow operation is usuallyfunctionIt means you can pass itlambda expressionOr method reference to perform an operation.

  3. Lazy evaluation: The intermediate operation of the stream will not be executed immediately, and will only be executed when a terminal operation is encountered. This means that the intermediate operation will form aassembly line, only start computing when the result is really needed, which helps optimize performance, especially when dealing with big data or complex operational chains.

  4. Can be parallel: Streams can be easily processed in parallel, using multi-core processors to improveperformance, just need tostream()Replace the method withparallelStream()method.

2. The steps to use stream

StreamOperations are divided intoIntermediate operationandTerminal operation
The intermediate operation returns aStream, allowing multiple operations to be performed continuously
Terminal operations will output a result or produce a side effect.

step:

  1. createStream

    • Created from data sources such as collections or arraysStream
    • useStreamstatic methods of the class, such as
  2. Perform intermediate operations

    • Intermediate operation asfilter, map, sortedWait, each operation will return a new oneStreamObject, other intermediate operations can be continued.
  3. Perform terminal operations

    • Terminal operation asforEach, collect, reduceThen, these operations will be closedStreamAnd generate results.

3. Common intermediate operations and terminal operations

Intermediate operation

The intermediate operation returns anotherStream, further operation is allowed.

  1. filter(Predicate<T>)
    Filter elements in the stream. Only elements that match the given predicate.

    list.stream().filter(x -> x > 10)  // Filter out elements larger than 10
    
    • 1
  2. map(Function<T, R>)
    Convert each element in the stream into another form and apply to each element through the given function.

    list.stream().map(x -> x * x)  // Replace each element with its square
    
    • 1
  3. flatMap(Function<T, Stream<R>>)
    andmapSimilar, but each input element can be mapped to multiple output elements (i.e., a list of elements).

    list.stream().flatMap(x -> Stream.of(x, x + 1))  // Convert each element to multiple elements
    
    • 1
  4. sorted()andsorted(Comparator<T>)
    Order elements in the stream naturally or use a custom comparator.

    list.stream().sorted()  // Natural sorting
    list.stream().sorted(Comparator.reverseOrder())  // Inverse order
    
    • 1
    • 2
  5. distinct()
    Returns a stream containing unique elements (according to(Object)Method to remove heavy weight).

    list.stream().distinct()
    
    • 1
  6. limit(long n)andskip(long n)
    limitIntercept the first n elements of the stream;skipSkip the first n elements.

    list.stream().limit(5)  // Take the first 5 elements
    list.stream().skip(5)  // Skip the first 5 elements
    
    • 1
    • 2

Terminal operation

Terminal operations generate results from the stream's pipeline.

  1. forEach(Consumer<T>)
    Perform the given action on each element.

    list.stream().forEach(System.out::println)  // Print each element
    
    • 1
  2. collect(Collector<T, A, R>)
    Converting streams to other forms is a very powerful operation, especiallyCollectorsClasses provide many convenient methods.

    List<Integer> newList = list.stream().collect(Collectors.toList());  // Collected List
    
    • 1
  3. reduce(BinaryOperator<T>)
    By reusing the given operation, combine elements in the stream and return aOptional

    Optional<Integer> sum = list.stream().reduce(Integer::sum);  //Sum
    
    • 1
  4. anyMatch(Predicate<T>), allMatch(Predicate<T>), noneMatch(Predicate<T>)
    Check if there is at least one element in the stream (anyMatch), all elements (allMatch), no elements (noneMatch) Match the given predicate.

    boolean hasEven = list.stream().anyMatch(x -> x % 2 == 0);  // Check if there are even numbers
    
    • 1
  5. count()
    Returns the number of elements in the stream.

    long count = list.stream().count();
    
    • 1
  6. min(Comparator<T>)andmax(Comparator<T>)
    Returns the minimum or maximum value in the stream according to the given comparator.

    Optional<Integer> min = list.stream().min(Integer::compare);
    Optional<Integer> max = list.stream().max(Integer::compare);
    
    • 1
    • 2

Four. Example

List<Employee> employees = getEmployees(); // Assume this is a list of employees taken from the database or elsewhere
List<Employee> filteredEmployees = employees.stream()   // Create Stream
    .filter(e -> e.getAge() > 30)           // Filter age
    .sorted(Comparator.comparing(Employee::getName))  // Sort by name
    .collect(Collectors.toList());          // Collect new list

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6