1. What is a Stream

A Stream is a data channel used to manipulate sequences of elements generated by data sources (collections, arrays, and so on).

“Sets are about data, streams are about computation!”

Note:

  • 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.
  • A Stream can only be “consumed” once and is invalidated once traversed. Like a container iterator, to iterate again you must regenerate a new Stream

2. Stream Operation instance

Take the names of all people older than 18, sort them by dictionary, and print them to the console

public class StreamDemo {


    private static List<Person> persons = Arrays.asList(
            new Person("CJK".19."Female"),
            new Person("BODUO".20."Female"),
            new Person("JZ".21."Female"),
            new Person("anglebabby".18."Female"),
            new Person("huangxiaoming".5."Male"),
            new Person("ROY".18."Male"));public static void main(String[] args) throws IOException {
        persons.stream().filter(x -> x.getAge() >= 18).map(Person::getName).sorted().forEach(System.out::println); }}Copy the code
BODUO
CJK
JZ
ROY
anglebabby
Copy the code

3. The operation of Stream has three steps

  1. createStreamA data source (e.g., collection, array) that retrieves a stream
  2. Intermediate operation A chain of intermediate operations that processes data from a data source
  3. Termination operation (terminal operation) A termination operation that performs an intermediate chain of operations and produces a result

4. To create Steam

  • CollectionTwo methods are providedstream()withparallelStream()
  • throughArraysIn thestream()Gets an array stream
  • throughStreamClass static methodsof()
  • Creating an infinite stream
public void test1(a){
    Collection provides two methods stream() and parallelStream().
    List<String> list = new ArrayList<>();
    Stream<String> stream = list.stream(); // Get a sequential stream
    Stream<String> parallelStream = list.parallelStream(); // Get a parallel stream

    //2. Get an array stream from stream() of Arrays
    Integer[] nums = new Integer[10];
    Stream<Integer> stream1 = Arrays.stream(nums);

    //3. Static method of() on Stream
    Stream<Integer> stream2 = Stream.of(1.2.3.4.5.6);
    
    //4. Create an infinite stream
    / / iteration
    Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
    stream3.forEach(System.out::println);

    / / generated
    Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
    stream4.forEach(System.out::println);
}
Copy the code

Question:

Which of the following ways to create a Stream is correct (multiple choices) => C,D,E,F

A. Steam.newInstanceOf()

B. Collection.of()

C. Collection. The stream () or collections. ParallelStream ()

D.Stream.of()

E.S tream. The generate () or Stream. Iterate ()

F.Arrays.stream()

5. Perform intermediate operations

  1. Screening and sectioning
    • Filter – Receives a Lambda and excludes certain elements from the stream.
    • Limit – Truncates the stream so that it does not exceed a given number of elements.
    • Skip (n) — Skip the element, returning a stream with the first n elements thrown away. If there are less than n elements in the stream, an empty stream is returned. And limit (n) complement each other
    • Distinct — Filter to remove duplicate elements by hashCode() and equals() of the elements generated by the stream
  2. mapping
  • Map – Receives lambdas, converts elements to other forms or extracts information. Take as an argument a function that is applied to each element and mapped to a new element.
  • FlatMap – Takes a function as a parameter, replaces each value in the stream with another stream, and joins all streams into a single stream
  1. The sorting
  • Sorted () – Naturally sorted
  • Sorted (Comparator com) – Custom sort

Question:

  1. Have an arrayThe Integer [] ary =,2,3,4,5,6,7,8,9,10 {1}And take out the third to fifth elements in the middle
List<Integer> collect = Arrays.stream(ary).skip(2).limit(3).collect(Collectors.toList());
Copy the code
  1. Have an arrayThe Integer [] ary =,2,2,3,4,5,6,6,7,8,8,9,10 {1},Take out the even numbers and remove the duplicates
List<Integer> list = Arrays.stream(ary).filter(x -> x % 2= =0).distinct().collect(Collectors.toList());

Set<Integer> integerSet = Arrays.stream(ary).filter(x -> x % 2= =0).collect(Collectors.toSet());
Copy the code
  1. I have a two-dimensional array, and I want to combine the arrays into a one-dimensional array and sort them(1,2,3,4,5... 12)
Integer ary = {{3.8.4.7.5}, {9.1.6.2}, {0.10.12.11}}; Arrays.stream(ary).flatMap(item->Arrays.stream(item)).sorted().forEach(System.out::println);Copy the code

6. Terminate the operation

Terminal operations generate results from the pipeline of streams. The result can be any value that is not a stream, such as List, Integer, or even void.

Find and match

interface instructions
allMatch(Predicate p) Check that all elements match
anyMatch(Predicate p) Check that at least one element matches
noneMatch(Predicate p) Check that all elements are not matched
findFirst() Returns the first element
findAny() Returns any element in the current stream
count() Returns the total number of elements in the stream
max(Comparator c) Returns the maximum value in the stream
min(Comparator c) Returns the minimum value in the stream
forEach(Consumer c) The iteration

Question:

The Integer [] ary =,2,3,4,5,6,7,8,9,10 {1}

  1. Check that all elements are less than 10
boolean result1 = Arrays.stream(ary).allMatch(x -> x < 10);
System.out.println(result1);
Copy the code
  1. Check that at least one element is less than 2
boolean result2 = Arrays.stream(ary).anyMatch(x -> x < 2);
System.out.println(result2);
Copy the code
  1. Check that none of the elements are greater than 10
boolean result3 = Arrays.stream(ary).noneMatch(x -> x > 2);
System.out.println(result3);
Copy the code
  1. Returns the first element
Optional<Integer> first = Arrays.stream(ary).findFirst();
System.out.println(first.get());
Copy the code
  1. How many elements does ary have
long count = Arrays.stream(ary).count();
System.out.println(count);
Copy the code
  1. Find the maximum in ary
Optional<Integer> max = Arrays.stream(ary).max(Integer::compareTo);
System.out.println(max.get());
Copy the code
  1. Find the minimum in ary
Optional<Integer> min = Arrays.stream(ary).min(Integer::compareTo);
System.out.println(min.get());
Copy the code
  1. Loop over to print an even number in ary
Arrays.stream(ary).filter(x -> x % 2= =0).forEach(System.out::println);
Copy the code

7. Reduction

Reduce (T iden, BinaryOperator b) can combine elements ina stream repeatedly to obtain a value. Return T

Reduce (BinaryOperator b) can combine elements ina stream repeatedly to obtain a value. Returns the Optional < T >

Question: Calculate the total score of all students

Integer all = persons.stream().map(Person::getScore).reduce((integer, integer2) -> integer + integer2).get()
Copy the code

Collected 8.

collect(Collector c)

Convert the stream to another form. Receives an implementation of the Collector interface, a method for summarizing elements in a Stream

The implementation of methods in the Collector interface determines how collection operations (such as collecting lists, sets, maps) are performed on streams.

The Collectors class provides many static methods that make it easy to create common collector instances

1. Specific methods and examples are as follows:

  • ToList List collects elements from the stream into the List
List<Person> emps= list.stream().collect(Collectors.toList());
Copy the code
  • ToSet Set collects elements from the stream into a Set
Set<Person> emps= list.stream().collect(Collectors.toSet());
Copy the code
  • ToCollection Collection collects elements from the stream into the created Collection
Collection<Person> emps=list.stream().collect(Collectors.toCollection(ArrayList::new));
Copy the code
  • Counting Long counts the number of elements in the stream
long count = list.stream().collect(Collectors.counting());
Copy the code
  • Summing Int Integer Sum of Integer attributes of elements in the stream
int total=list.stream().collect(Collectors.summingInt(Person::getAge));
Copy the code
  • We would calculate the average value of the Integer attributes of the elements in the stream
double avg= list.stream().collect(Collectors.averagingInt(Person::getAge));
Copy the code
  • SummarizingInt IntSummaryStatistics Collects statistics about the Integer attribute in the flow. Average value
Int SummaryStatisticsiss= list.stream().collect(Collectors.summarizingInt(Person::getAge));
Copy the code
  • Joining String Each String in a connection stream
String str= list.stream().map(Person::getName).collect(Collectors.joining());
Copy the code
  • MaxBy Optional Selects the maximum value based on the comparator
Optional<Person> max= list.stream().collect(Collectors.maxBy(comparingInt(Person::getSalary)));
Copy the code
  • MinBy Optional Selects the minimum value based on the comparator
Optional<Person> min = list.stream().collect(Collectors.minBy(comparingInt(Person::getSalary)));
Copy the code
  • A type resulting from a reducing starts with an initial value that acts as an accumulator and reduces to a single value by combining elements in the stream one by one using a BinaryOperator
int total=list.stream().collect(Collectors.reducing(0, Person::getSalar, Integer::sum));
Copy the code
  • The type returned by the collectingAndThen conversion function wraps around another collector and converts the function to its result
int how= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));
Copy the code
  • GroupingBy Map

    Streams groups according to an attribute value. The attribute value is K, and the result is V
    ,>
Map<Person.Status,List<Person>> map= list.stream().collect(Collectors.groupingBy(Person::getStatus)); PartitioningBy Map<Boolean, List<T>> basedtrueorfalsePartition Map < Boolean, List < Person > > vd = List. The stream () collect (Collectors. PartitioningBy (Person: : getManage));Copy the code

Practice 2.

The Integer [] ary =,2,3,4,5,6,7,8,9,10 {1}

  1. Obtain the maximum number of Collectors
Optional<Integer> collect = Arrays.stream(ary).collect(Collectors.maxBy(Comparator.comparing(x -> x)));
        System.out.println(collect.get());
Copy the code
  1. Obtain the average value of Collectors
IntSummaryStatistics collect1 = Arrays.stream(ary).collect(Collectors.summarizingInt(x -> x));
System.out.println(collect1.getAverage());
Copy the code
  1. A joining output “1:2:3:4:5:6:7:8:9:10”
String collect2 = Arrays.stream(ary).map(x -> x.toString()).collect(Collectors.joining(":"));
System.out.println(collect2);
Copy the code
  1. Find the sum of the ARY array using taylor. reducing
int total=Arrays.stream(ary).collect(Collectors.reducing(0, x->x, Integer::sum));
System.out.println(total);
Copy the code
  1. Run the Collectors. Counting command to obtain the number of ary
Long collect3 = Arrays.stream(ary).collect(Collectors.counting());
System.out.println(collect3);
Copy the code

3. Question:

  1. Take all the names of the Person object and put them in the List collection
List<String> collect2 = persons.stream().map(Person::getName).collect(Collectors.toList());
Copy the code
  1. Find the average score, total score, highest score, lowest score, number of scores of the Person object collection
IntSummaryStatistics collect = persons.stream().collect(Collectors.summarizingInt(Person::getScore));
System.out.println(collect);
Copy the code
  1. According to the result of grouping, pass put one group, fail put another group
Map<Boolean, List<Person>> collect1 = persons.stream().collect(Collectors.partitioningBy(person -> person.getScore() >= 60));
System.out.println(collect1);
Copy the code
  1. WordCount
public static void main(String[] args) throws IOException {
    InputStream resourceAsStream = Person.class.getClassLoader().getResourceAsStream("aa.txt");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream));
    bufferedReader.lines().flatMap(x->Stream.of(x.split(""))).sorted().collect(Collectors.groupingBy(String::toString)).forEach((a,b)-> System.out.println(a+":"+b.size()));
    bufferedReader.close();
}
Copy the code