Introduction to the

StreamCall itflow

The structure of the flow

  1. Sources (various collections)
  2. Zero or more intermediate operations (modifications and operations on elements in a collection)
  3. Terminate operations (output, sum…)

Create a flow

public class StreamTest1 {
    public static void main(String[] args) {
        int[] a = new int[] {2.4.6.8.7.9.13.16.17};
        Integer[] b = new Integer[]{2.4.6.8.7.9.13.16.17};
        Stream stream = Stream.of(a);
        Stream stream1 = Stream.of("asdf"."Asdfsa"."sadgggg");
        Stream stream2 = Arrays.stream(b);// The basic data type is not an array, but an array of objects, such as String, Integer...List<Integer> list = Arrays.asList(b); Stream stream3 = list.stream(); }}Copy the code

Slightly special flow

  • IntStream
public class StreamTest2 {
    public static void main(String[] args) {
        IntStream.range(6.13).forEach( s -> System.out.print(s+""));// Open the left and close the right}}Copy the code

Continue to experience the flow

Multiply each element in the set by 2 and sum

public class StreamTest3 {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1.2.3.4.5);
        System.out.println(list.stream().map(i -> i * 2).reduce(0, (i, s) -> s = s + i)); }}Copy the code

  • Code definition

ifreduceThe first parameter is theta6, thensThe initial value of theta is theta6The final result is36the

moreover

Go on and experience

  • Turn the data in the stream into an array and print it.
  • You can use StreamtoArraymethods

public class StreamTest4 {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("AABB"."CCDD"."EEFF"."GGHH");
       // System.out.println(stream.count()); // Find the number of elements in stream
        String[] stringArray = stream.toArray(length -> new String[length]);
        // When toArray is called, the length is calculated automatically
        Arrays.asList(stringArray).forEach(System.out::println);
        // Convert an array to a collection. Implement forEach parameter Consumer with forEach and then reference method}}Copy the code

Stream.of(“AABB”,”CCDD”,”EEFF”,”GGHH”); You can’t think of it as an array, of(T…) Is a variable length argument, just means to throw in multiple arguments, is not an array

  • Or use method references
public class StreamTest4 {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("AABB"."CCDD"."EEFF"."GGHH");
        String[] stringArray = stream.toArray(String[]::new);// Reference constructorArrays.asList(stringArray).forEach(System.out::println); }}Copy the code

usestream.collect( . . .)

Continue to

Turn the data in the stream into a List

  • Let’s start with the one we know all aboutCollectors.toList()
public class StreamTest5 {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(11.22.33.44.55.66);
        List<Integer> list = stream.collect(Collectors.toList());
        list.forEach(l -> System.out.print(l+"")); }}Copy the code
  • One more that I don’t understand
public class StreamTest5 {
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(11.22.33.44.55.66);
 
       List<Integer> list2 = stream.collect( () -> new ArrayList<Integer>(),
       (resList,item) -> resList.add(item),
       (resList1,resList) -> resList1.addAll(resList));// stream.collect accepts 3 arguments
        list2.forEach(l -> System.out.print(l+""));/ / print}}Copy the code
  • The above code can be referenced using method references
List<Integer> list2 = stream.collect(ArrayList::new, ArrayList::add,
                ArrayList::addAll);

Copy the code

  • Look at the code

moreover

  • You might thinkCollectors.toList()Enough already

  • Description:Collectors.toList()Only returnArrayList, if necessaryLinkedListOr something, by handstream.collectImplementation of three parameters (provider, accumulator, combinator)

Use the artifact a little bitCollectors

  • stream.collect(Collectors.toList())I won’t say this
  • Collectors. ToCollection (Implementation class for collections ::new)// Get the set you want
public class CollectsTest {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("AABB"."CCDD"."EEFF"."GGHH");
                                                                  // Convert stream to ArrayList
        List<String> stringList = stream.collect(Collectors.toCollection(ArrayList::new)); System.out.println(stringList.getClass()); }}Copy the code

  • In the same way

public class CollectsTest {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("AABB"."CCDD"."EEFF"."GGHH");
                                                           // Convert stream to TreeSet
        Set<String> stringSet = stream.collect(Collectors.toCollection(TreeSet::new)); System.out.println(stringSet.getClass()); }}Copy the code

  • aboutCollectors. ToCollection (Implementation class for collections ::new)Implementation of or the beloved trio (provider, accumulator, combinator)

  • Concatenation, which concatenates different elements with the specified delimiter to form a String
public class CollectsTest {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("AABB"."CCDD"."EEFF"."GGHH");
        String str = stream.collect(Collectors.joining("00")); // Concatenate String with 00 delimiter
        System.out.println(str);
        // Collectors. Joining returns a String}}Copy the code

  • Uppercase the String element in the collection
public class StreamTest6 {
    public static void main(String[] args) {
        List<String> stringList = Arrays.asList("aabb"."ccdd"."eeff"."gghh"); stringList.stream().map(String::toUpperCase).forEach(System.out::println); }}Copy the code

Operates on elements of a List within a List and puts elements of multiple lists into a List

  • You might take it for granted

  • The right solution
public class FlatMap {
    public static void main(String[] args) {
        Stream<List<Integer>> listStream = Stream.of(Arrays.asList(2.4.7),Arrays.asList(8.8),Arrays.asList(13.19));
                                        // Flat mappingList<Integer> list = listStream.flatMap(ls -> ls.stream()).map(item ->item*item).collect(Collectors.toList()); list.forEach(System.out::println); }}Copy the code

Let’s do a couple more applications

andOptionalrelated

  • Experience infinite flowgenerate()
public class StreamTest7 {
    public static void main(String[] args) {
        Stream<String> stream = Stream.generate(UUID.randomUUID()::toString);// A new unordered Stream of infinite order
        stream.forEach(System.out::println);// The output will not end}}Copy the code
  • usefindFirst()To return toOptionalAnd encapsulate the first element
public class StreamTest7 {
    public static void main(String[] args) {
        Stream<String> stream = Stream.generate(UUID.randomUUID()::toString);// A new unordered Stream of infinite order
        stream.findFirst().ifPresent(System.out::println);
        // Check whether the return is empty Optional before performing other operations to prevent null pointer exceptions}}Copy the code

Another kind of infinite flow

  • iterate(final T seed, final UnaryOperator<T> f)
public class StreamTest7 {
    public static void main(String[] args) { 
                     Return I =(I +1)%2
        Stream.iterate(0 ,i -> (i+1) %2).forEach(System.out::println);// Infinite output 0 and 1}}Copy the code
  • Interrupt infinite flow
  • Defective operation, that is, the output is not infinite, but the stream is not interrupted
public class StreamTest7 {
    public static void main(String[] args) {
                                      // Remove duplicate elements, // extract the first 6 elements
        Stream.iterate(0 ,i -> (i+1) %2).distinct().limit(6).forEach(System.out::println);
        // Outputs only 0 and 1, but the program does not end}}Copy the code

  • End it normally
public class StreamTest7 {
    public static void main(String[] args) {
        Stream.iterate(0 ,i -> (i+1) %2).limit(6).distinct().forEach(System.out::println); }}Copy the code

It is normal to intercept a fixed number of elements and then remove duplicates. Because the stream is infinite, the work will not be finished if it is removed first, so it must be intercepted first, the stream becomes a fixed length, and the program can be finished.