“This is the 13th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

StreamAPI

Stream focuses on various efficient aggregate operations and bulk data operations on data sources. The Stream API treats the data source it processes as a Stream, which is transmitted and computed in a Pipeline. The supported operations include filtering, sorting, aggregation, etc., and the final processing result is obtained when it reaches the end point.

Overview: Stream is concerned with operations on data, dealing with the CPU.

  • Collections are concerned with storing data, dealing with memory

    • The Stream itself does not store elements.
    • Stream does not change the source object. Instead, they return a new Stream holding the result
    • The Stream operation executes lazily. This means they wait until they need results
    • Stream can be created in both serial and parallel modes.
  • Stream execution process

    • Instantiation of Stream
    • A series of intermediate operations (filtering, mapping,…)
    • Termination of operations
  • Description:

    • An intermediate chain of operations that processes data from the data source.
    • Once the termination operation is performed, the intermediate operation chain is executed and the result is produced. After that, it won’t be used again.

Simple to use

1. Create a Stream

Method one: through collections

List<Integer> list = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); //default Stream<E> Stream (): returns a sequential Stream<Integer> Stream = list.stream(); ParallelStream = list.parallelstream (); //default Stream<E> parallelStream(): return a parallelStream <Integer> parallelStream = list.parallelstream ();Copy the code

Method two: Through an array

Int [] arr = new int [] {1, 2, 3, 4, 5}; Static <T> Stream<T> Stream (T[] array) : Returns a Stream IntStream = array.stream (arr);Copy the code

Method 3: Through the of() method of Stream

    Stream<Integer> integerStream = Stream.of(1, 2, 3, 4, 5);
Copy the code

Create a Stream infinite Stream

// iterate //public static<T> Stream<T> iterate(final T seed, Iterate (0, T -> T +2).limit(10).foreach (system.out ::println);Copy the code

Stream intermediate operation

Get some data:

class BoyData{ public static List<Boy> getBoy(){ List<Boy> list=new ArrayList<>(); list.add(new Boy("aa",20)); list.add(new Boy("bb",30)); list.add(new Boy("cc",25)); list.add(new Boy("dd",23)); list.add(new Boy("ee",28)); list.add(new Boy("ee",28)); list.add(new Boy("ee",28)); return list; }}Copy the code

Look at the following operation

2.1. Screening and sectioning

  • Filter (Predicate P) : Receives Lambda and excludes certain elements from the stream.
List<Boy> boyList = BoyData.getBoy(); // Create a Stream for subsequent operations. Stream<Boy> boyStream = boyList.stream(); // Exclude boys younger than 25 and print. boyStream.filter(b->b.getAge()>25).forEach(System.out::println);Copy the code
  • Limit (n) : Truncates the stream so that it does not exceed a given number of elements.
// Take the first two pieces of data and output them. boyStream.limit(2).forEach(System.out::println);Copy the code
  • Skip (n) : Skip elements, returning a year in which the first n elements were thrown away. If there are less than n elements in the stream, an empty stream is returned.
Skip (2). ForEach (system.out ::println);Copy the code
  • Distinct () : Filter to remove duplicate elements by hashCode() and equals() of the elements generated by the stream.
Distinct ().foreach (system.out ::println);Copy the code

Important: At this point you need to override the equals and HashCode methods in the javaBean, otherwise the methods will be invalidated.

Rewrite code:

@Override public int hashCode() { int result; long temp; result = 1; result = 31 * result + (name ! = null ? name.hashCode() : 0); result = 31 * result + age; temp = Double.doubleToLongBits(age); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object o) { if(this==o){ return true; } if(o == null||getClass()! =o.getClass()){ return false; } Boy boy = (Boy) o; if(age ! =boy.age){ return false; } return name ! =null? name.equals(boy.name):boy.name ==null; }Copy the code

2.2, sorting,

// Integers <Integer> integers = Arrays. AsList (18, 43, 66, 22, 4, 97, 12); integers.stream().sorted().forEach(System.out::println); Sorted ((b1,b2)-> integer.sorted (b1.getage (), b2.getage ())).sorted(system.out ::println);Copy the code

Stream Terminates a Stream

True fragrance operation:

  • AllMatch (Predicate P) : Checks whether all elements match.
    • See if everyone is older than 20

      boolean allMatch = boyStream.allMatch(b -> b.getAge() > 19); System.out.println(" Is everyone older than 19:"+(allMatch==true? Yes ":" No ");Copy the code
    • Results:

  • AnyMatch (Predicate P) : Checks whether at least one element matches.
  • NoneMatch (Predicate P) : Checks if there are no matching elements.
  • FindFirst () : Returns the first element.
    • Returns the first boy

        Optional<Boy> first = boyStream.findFirst();
        System.out.println(first);
      Copy the code
    • Results:

  • FindAny () : Returns a random element in the current stream.
  • Count () : Returns the total number of elements in the stream.
    • It shows how many boys there are

        long count = boyStream.count();
        System.out.println(count);
      Copy the code
    • Results:

  • Max (Comparator c) : Returns the maximum value in the stream.
    • Output the maximum age value

        Optional<Integer> maxBoy = boyStream.map(boy -> boy.getAge()).max((b1,b2)->b1.compareTo(b2));
        System.out.println(maxBoy.get());
      Copy the code
    • Results:

  • Min (Comparator c) : Returns the minimum value in the stream.
  • ForEach (Consumer C) : Internal iteration.
    • Output all boys

        boyStream.forEach(System.out::println);
      Copy the code
    • Results:

  • statute
    • Reduce () — You can combine elements in a stream repeatedly to get a value and return it.

    • Add up the ages of all boys

          Optional<Integer> sumAge = boyStream.map(boy -> boy.getAge()).reduce((b1, b2) -> b1 + b2);
          System.out.println(sumAge.get());
      Copy the code
    • The results of

  • collect
    • Finds boys younger than 26 and returns them stored in a collection.

        List<Boy> boyList1 = boyStream.filter(boy -> boy.getAge() < 26)
        .collect(Collectors.toList());
        boyList1.forEach(System.out::println);
      Copy the code
    • Results:

Thanks for watching, that’s all! I hope it will be your new favorite ~