Stream-List conversion

1. What is Stream?

Stream is a key abstract concept for Java 8 to deal with collections. It can perform very complex search, filter, and filter operations on collections.

Two, the basic operation of Stream

1. Create Stream

Get streams from collections and arrays.

2. Intermediate operation

Operate on the data of the data source.

3. Terminate operation

The termination operation executes the intermediate operation chain and produces the result.
It should be noted here that the closing operation is required after the flow operation is completed.

Three, the specific operation of Stream

1. Intermediate operation-screening and slicing

filter: Receive Lambda expressions and exclude certain operations from the stream.
limit: cut off the stream so that the element does not exceed the given object.
skip(n): skip elements, return a stream that discards the first n elements.
distinct: filter, remove duplicate elements through hashCode() and equals() generated by the stream.

2. Intermediate operation-mapping

map: Receive Lambda, convert elements into other forms or extract information. Receive a function as a parameter, the function will be applied to each element, and map it into a new element.
flatMap: Receives a function as a parameter, replaces each value in the stream with another stream, and then connects all streams into one stream.

Right here we want to convert List to int array


 public static void main(String[] args) {
    
    
        List<Integer> list = new ArrayList<>();

        list.add(1);
        list.add(2);

        int[] arr = list.stream().mapToInt(Integer::intValue).toArray();
     for(int i:arr){
    
    
         System.out.println(i);
     }
    }

3. Intermediate operation-sort

sorted(): Natural sort
sorted (Comparator com): Custom sort

5. Termination operation-find and match

  • allMatch-check whether all elements are matched
  • anyMatch-check if at least one element is matched
  • noneMatch-check if 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-returns the maximum value in the stream
  • min-returns the minimum value in the stream

The data requested by the url network used here.

to sum up

Here is what I want to tell you, you can use stream operations more, otherwise you can only use a loop to convert.

Guess you like

Origin blog.csdn.net/qq_44688861/article/details/115291086