Chapter 3 Stream API, Chapter 3 streamapi

Source: Internet
Author: User
Tags stream api

Chapter 3 Stream API, Chapter 3 streamapi

Example:

1 List <String> strList = Arrays. asList ("zhaojigang", "nana", "tianya", "nana"); 2 Stream <String> streamList = strList. stream (); // convert the set to stream3 strList = streamList. distinct (). filter (str->! Str. equals ("tianya"). sorted (String: compareTo). collect (Collectors. toList (); 4 strList. forEach (System. out: println );

Note:

  • Line 1: Create an array and convert it to List
  • Row 2: Create a stream based on the List
  • Row 3: deduplication of the stream --> select --> sort --> stream to List
  • Row 4: traverse the List

The above code shows the convenience of stream API. Of course, the above Code can be simpler, as shown in the following code:

Arrays.asList("zhaojigang","nana","tianya","nana").stream().distinct().filter(str->!str.equals("tianya")).sorted(String::compareTo).collect(Collectors.toList()).forEach(System.out::println);

The above code has an easy-to-error point: filter is selection rather than filtering, that isFilter is the element that meets the conditions..

1. Create a Stream

Three Common APIs:

  • Set --> Stream: stream ()
  • Array --> Stream: Stream. of (T t) or Arrays. stream (T [] t)
  • Any element --> Stream: Stream. of (T... values)
1 List <String> strList = Arrays. asList ("zhaojigang", "nana", "tianya", "nana"); 2 Stream <String> streamList = strList. stream (); // convert the set to stream 3 4 String [] strArray = {"java", "c ++", "c "}; 5 Stream <String> streamArray = Stream. of (strArray); // convert the array to Stream 6 Stream <String> streamArray2 = Arrays. stream (strArray); // convert the array to Stream 7 8 Stream <String> streamPartArray = Arrays. stream (strArray, 0, 2); // converts some arrays, range: [) 9 10 Stream <String> streamSelf = Stream. of ("python", "basic", "php"); // any element

Another type is Stream. generate (Supplier <T> s), which is used to generate infinite streams ).

 

Ii. Stream 2 array/collection/String/map

1. stream2array

1 Stream <String> strStream = Stream. of ("java", "c ++", "c", "python"); 2 Object [] objectArray = strStream. toArray (); // only Object [] 3 String [] strArray = strStream can be returned. toArray (String []: new); // constructor reference (similar to method reference), you can return String []

Note:

The constructor reference (similar to method reference) can be used to construct an array of the object type.

 

2. stream2collection

1 List <String> strList = strStream. collect (Collectors. toList (); // returns the List2 Set <String> strSet = strStream. collect (Collectors. toSet (); // return set3 ArrayList <String> strArrayList = strStream. collect (Collectors. toCollection (ArrayList: new); // collect to the specified List set, for example, collect to ArrayList

Note:

A constructor reference can be used to construct a collection of entity types.

 

3. concatenate the elements in stream (joining (), joining (","))

1 Stream <String> strStream = Stream. of ("java", "c ++", "c", "python"); 2 String str = strStream. collect (Collectors. joining (); // concatenates all strings. The result is javac ++ cpython3 System. out. println (str); 4 5 String str2 = strStream. collect (Collectors. joining (","); // concatenate all strings and separate them with ",". The result is java, c ++, c, and python6 System. out. println (str2 );

 

4. stream2map (toMap, toConcurrentMap)

1 Stream <String> strStream = Stream. of ("java", "c ++", "c", "python"); 2 Map <String, Integer> map1 = strStream. collect (Collectors. toMap (Function. identity (), (x)-> 0); 3 // Function. identity () --> returns the elements in strStream. Both of the two parameters of the toMap method are Function interface type. Therefore, even if the second parameter is set to only 0, 0 cannot be written directly, you can use the above method to operate 4 5 for (String key: map1.keySet () {6 System. out. println ("key:" + key + "->" + "value:" + map1.get (key); 7} 8 // result 9/* 10 key: python-> value: 011 key: c ++-> value: 012 key: c-> value: 013 key: java-> value: 014 */

Note:

  • ToMap --> convert stream to map
  • Function. identity () --> returns the elements in stream.

If the key is repeated, the problem "duplicate key" will occur. Solve the problem as follows (add the third parameter ):

1 Stream <String> strStream = Stream. of ("java", "c ++", "c", "python", "java"); 2 Map <String, Integer> map1 = strStream. collect (Collectors. toMap (Function. identity (), // key3 (x)-> 0, // value4 (existingValue, newValue)-> existingValue); // if the key is repeated, take the old value

You need to specify the specific type of the returned map (add the fourth parameter ).

1 Map <String, Integer> map1 = strStream. collect (Collectors. toMap (Function. identity (), // key2 (x)-> 0, // value3 (existingValue, newValue)-> existingValue, // if the key is repeated, take the old value 4 TreeMap :: new); // returns TreeMap

Note: Each toMap corresponds to a corresponding toConcurrentMap.

3. filter (Predicate p)

Note: selection rather than Filtering.

1         Stream<String> streamSelf = Stream.of("python","basic","php");2         streamSelf.filter(str->str.startsWith("p")).forEach(System.out::println);

Note:

  • Stream can also be foreach, there is no need to convert it into a set and then foreach

The better way to write is probably the following:

1         Predicate<String> startCondition = str->str.startsWith("p");2         streamSelf.filter(startCondition).forEach(System.out::println);

Note:Extract conditions (usually lambda expressions). This method is clear when multiple conditions exist.

Note:Function interfaces = lambda expressions (that is, lambda expressions can only be returned as function interfaces)

 

4. map (Function mapper)

Function: operate each element in the stream.

1         Stream<String> streamSelf = Stream.of("python","basic","php");2         streamSelf.map(String::toUpperCase).forEach(System.out::println);

Description: converts all strings in the stream to uppercase.

 

V. reduce

Function: Performs aggregation on each element of stream.

1 Stream <Integer> performancestream = Stream. of (1, 2, 3, 4, 5); 2 Optional <Integer> sumOption = performancestream. reduce (x, y)-> x + y); // calculate 1 + 2 + 3 + 4 + 5, that is, aggregate and compute the elements in the element, while map calculates each element separately (Note: If stream is null, it will produce invalid results and must be received using Optional) 3 // Optional <Integer> sumOption = performancestream. reduce (Integer: sum); // calculate 1 + 2 + 3 + 4 + 5, that is, aggregate the elements in the element, while map calculates 4 5 Integer result = performancestream for each element. reduce (0, Integer: sum); // 0 is the Identifier value, that is, 0 + 1 + 2 + .. + 5. If the entire stream is null, the ID value is returned. 6 System. out. println (result );

Note: The preceding is a simple form of reduce, that is, the inline function is (T, T)-> T, that is, the return value is the same as the parameter type, for scenarios with different return values and parameter types, you need to write your own functions (rarely used)

 

6. Optional

Two usage methods:

  • IfPresent (xxx): Execute xxx If it exists. If it does not exist, nothing will be executed.
  • OrElse (xxx): If yes, the system returns an existing value. If no value exists, the system returns xxx (which can be understood as the default value)
1 Stream <String> optionalStream = Stream. of ("java", "python", "basic"); 2 Optional <String> optionValue = optionalStream. filter (str-> str. startsWith ("p ")). findFirst (); 3 optionValue. ifPresent (str-> System. out. println (str); // if optionalValue is true, that is, if str exists, str is output. Of course, the following 4 String str = optionValue can also be used. orElse ("xxx"); // If optionValue is false, that is, if a string starting with p does not exist, use "xxx" to replace 5 System. out. println (str );

 

 

VII. limit skip contact

1. limit (long size)

Purpose: intercept the first size elements of stream.

1 Stream <String> streamSelf = Stream. of ("python", "basic", "php"); 2 streamSelf. limit (2 ). forEach (System. out: println); // intercept the first two

2. skip (long size)

Purpose: Skip the money and size elements of stream.

1 Stream <String> streamSelf = Stream. of ("python", "basic", "php"); 2 streamSelf. skip (2 ). forEach (System. out: println); // skip the first two

3. contact (Stream <T>, Stream <T>)

Function: concatenates two streams.

1         Stream<String> streamSelf = Stream.of("python","basic","php");2         Stream<String> streamSelf2 = Stream.of("python2","basic2","php2");3         Stream.concat(streamSelf, streamSelf2).forEach(System.out::println);

 

VIII. Aggregate Function count max min findFirst findAny anyMatch allMatch noneMatch

1 Stream <String> streamSelf = Stream. of ("python", "basic", "php", "B"); 2 System. out. println (streamSelf. count (); // calculate the number of elements in the stream. 3 Optional <String> largest = streamSelf. max (String: compareToIgnoreCase); // search for the maximum value of 4 if (largest. isPresent () {5 System. out. println (largest. get (); 6}

Note: The same is true for min functions.

NOTE: For the use of Optional, the above is the worst form. For details, see "6 ".

1 Optional <String> firstMatch = streamSelf. filter (str-> str. startsWith ("B ")). findFirst (); // search for the first qualified element 2 firstMatch. ifPresent (System. out: println); // This Is The First Optional usage 3 4 Optional <String> anyMatch = streamSelf. parallel (). filter (str-> str. startsWith ("B ")). findAny (); // any element that meets the conditions in the returned set, which is very good for Parallel Processing (because the entire computing will end if one thread finds multiple threads) 5 if (anyMatch. isPresent () {6 System. out. println (anyMatch. get (); // The result here may be B, which may be basic 7} 8 9 boolean isAnyMatch = streamSelf. parallel (). anyMatch (str-> str. startsWith ("c"); // whether there is a condition 10 System in the set. out. println (isAnyMatch); 11 12 Stream <String> streamSelf3 = Stream. of ("basic", "B"); 13 boolean isAllMatch = streamSelf3.parallel (). allMatch (str-> str. startsWith ("B"); // whether all elements in the Set meet the condition 14 System. out. println (isAllMatch); 15 16 boolean isAllNotMatch = streamSelf. parallel (). noneMatch (str-> str. startsWith ("p"); // whether no element in the Set meets the condition 17 System. out. println (isAllNotMatch );

Note:

  • Optional: ifPresent () --> if there is output, if there is no, nothing to do
  • Parallel (): converts a stream to a parallel stream. When using a parallel stream, pay attention to thread security.

 

 

 

 

8,

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.