Java Stream Stream processing
I. The concept of flow
Structure of 1.
- Flow to obtain
- Conversion operations: There can be more than one
- Terminate operation: There can be only one
Type 2.
-
Stream () : single pipe
-
parallelStream()
- Multi-pipe, parallel streaming processing, implemented using ForkJoinPool
- Enforce order: forEachOrdered()
List<Integer> list = Arrays.asList(1.2.3.4.5.6.7); // Result: 1234567 list.stream().forEach(System.out::print); // Result: 5726134 list.parallelStream().forEach(System.out::print); // Result: 1234567 list.parallelStream().forEachOrdered(System.out::print); Copy the code
3. functional interfaces
-
An interface has one and only one abstract method
-
Common interface
interface parameter The return value category Consumer T void Consumer interface Supplier None T Supply interface Function T R Functional interface Predicate T boolean Assertion interface
Lambda expressions
- ‐> {code statements}
- Used to simplify writing functional interfaces
- Can delay running, improve performance
Second, stream acquisition
1. Collection subinterface
-
Call the stream() method directly
-
List
-
Set
-
Vector
List<String> list = new ArrayList<>(); Stream<String> stream1 = list.stream(); Set<String> set = new HashSet<>(); Stream<String> stream2 = set.stream(); Vector<String> vector = new Vector<>(); Stream<String> stream3 = vector.stream(); Copy the code
2. Map
-
It is not a Collection subinterface, and its K-V data structure does not conform to the characteristics of confluence elements. Therefore, it needs to obtain the data according to Key, Value, and Entry respectively
Map<String, String> map = new HashMap<>(); // ... Stream<String> keyStream = map.keySet().stream(); Stream<String> valueStream = map.values().stream(); Stream<Map.Entry<String, String>> entryStream = map.entrySet().stream(); Copy the code
3. Array
-
You can’t add a default method to the array, so use the stream.of () method
String[] array = { "Zhang Wuji"."Zhang Cuishan"."Zhang Sanfeng"."Zhang Yi Yuan" }; Stream<String> stream = Stream.of(array); Copy the code
Second, conversion operation
1. filter( T -> boolean )
-
Filter data, reserving elements with true condition
List<Integer> list = Arrays.asList(20.23.25.28.30.33.37.40); // Filter data sets greater than or equal to 30 from the specified data set List<Integer> collect = list.stream().filter(x -> x >= 30).collect(Collectors.toList()); // Result: [30, 33, 37, 40] System.out.println(collect); Copy the code
2. map( T -> R )
-
Convert data and store the converted data in reflux
List<String> list = Arrays.asList("1"."2"."3"."4"."5"."6"); List<Long> collect1 = list.stream().map(x -> Long.parseLong(x)).collect(Collectors.toList()); // Result: [1, 2, 3, 4, 5, 6] System.out.println(collect1); // Result: 111111 list.stream().mapToInt(x -> x.length()).forEach(System.out::print); System.out.println(""); // Result: 111111 list.stream().mapToLong(x -> x.length()).forEach(System.out::print); System.out.println(""); // Result: 1.01.01.01.01.01.0 list.stream().mapToDouble(x -> x.length()).forEach(System.out::print); Copy the code
3. flatMap( T -> Stream )
-
Map elements in a flow to a flow, and connect each flow to a flow
List<List<String>> list = new ArrayList<List<String>>(){{ add(Lists.newArrayList("a"."b"."c")); add(Lists.newArrayList("d"."e"."f")); add(Lists.newArrayList("j"."k"."y")); }}; // Results: [a, B, C], [D, e, f], [J, k, Y]] System.out.println(list); List<String> collect = list.stream().flatMap(List::stream).collect(Collectors.toList()); [a, b, C, D, e, f, j, k, y] System.out.println(collect); Copy the code
4. distinct()
-
The element is de-duplicated, and the bottom layer uses equals() to compare
List<String> list = Arrays.asList("a"."b"."ab"."abc"."a"."ab"."a"."abcd"."bd"."abc"); List<String> collect = list.stream().distinct().collect(Collectors.toList()); // Result: [a, b, ab, ABC, abcd, bd] System.out.println(collect); Copy the code
5. sorted( T -> boolean )
-
Order elements by implementing the Comparable interface or custom comparator
List<Integer> list = Arrays.asList(5.3.7.1.4.6); List<Integer> collect = list.stream().sorted((a, b) -> a.compareTo(b)).collect(Collectors.toList()); // Result: [1, 3, 4, 5, 6, 7] System.out.println(collect); Copy the code
6. limit( num )
-
Limit the number of elements returned
List<String> list = Arrays.asList("a"."b"."ab"."abc"."a"."ab"."a"."abcd"."bd"."abc"); List<String> collect = list.stream().limit(3).collect(Collectors.toList()); // Result: [a, b, ab] System.out.println(collect); Copy the code
7. skip( num )
-
Skip the element
List<String> list = Arrays.asList("a"."b"."ab"."abc"."a"."ab"."a"."abcd"."bd"."abc"); List<String> collect = list.stream().skip(5).collect(Collectors.toList()); // Result: [ab, a, abcd, bd, ABC] System.out.println(collect); Copy the code
8. peek( T -> void )
-
Elements are picked out for manipulation, but the resulting element is not returned to the stream
List<String> list = Arrays.asList("a"."b"."ab"."abc"."a"."ab"."a"."abcd"."bd"."abc"); // Result: abababcaabaabcdbdabc list.stream().peek(x -> x.toUpperCase()).forEach(System.out::print); // Result: ABABABCAABAABCDBDABC list.stream().map(x -> x.toUpperCase()).forEach(System.out::print); Copy the code
3. Terminate the operation
1. forEach
-
ForEach: supports parallel processing
-
ForEachOrdered: Forces the processing to be orderly and slow
List<String> list = Arrays.asList("a"."b"."ab"); // Result: A, B, ab list.stream().forEach(x -> System.out.print(x+' ')); System.out.println(""); // Can be simplified // Result: A, B, ab list.forEach(x -> System.out.print(x+' ')); System.out.println(""); // Result: A, B, ab list.stream().forEachOrdered(x -> System.out.print(x+' ')); Copy the code
2. collect
-
ToMap: Transforms the data stream into a Map containing key/value elements
-
ToSet: Converts a data stream to a Set containing elements that cannot be repeated
-
ToList: Converts the data stream to a List containing ordered elements
-
Joining: a joining separator between elements that returns a string
-
GroupingBy: Groups a List into a Map
-
Couting: Count elements
-
MaxBy: Get the largest element
-
MinBy: Gets the smallest element
-
SummarizingInt: Summarizes elements of type Integer, which returns IntSummaryStatistics. You can then call a specific method to collect statistics
- GetCount: indicates the number of statistics
- GetSum: sum
- GetMin: obtains the minimum value
- GetMax: obtains the maximum value
- GetAverage: Obtain averages
-
SummarizingLong: Summary Long element, same as summarizingInt
-
SummarizingDouble: summarizingDouble element, same as summarizingInt
-
AveragingInt: Retrieves the average value of an Integer element and returns a Double
-
AveragingLong: Retrieves the average value of the Long element and returns a Double
-
AveragingDouble: Retrieves the average value of Double elements and returns a Double
-
Mapping: Gets a mapping that returns a portion of the original element as a new element
List<String> list0 = Arrays.asList("a"."b"."ab"); Map<String, String> collect0 = list0.stream().collect(Collectors.toMap(String::new, Function.identity())); {ab=ab, a=a, b=b} System.out.println(collect0); List<String> list = Arrays.asList("a"."b"."ab"."a"."b"."ab"); List<String> collect1 = list.stream().collect(Collectors.toList()); // Result: [a, b, ab, a, b, ab] System.out.println(collect1); // result: [a, ab, b] Set<String> collect2 = list.stream().collect(Collectors.toSet()); System.out.println(collect2); String collect3 = list.stream().collect(Collectors.joining(",")); A,b,ab,a,b,ab System.out.println(collect3); Map<String, Long> collect4 = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); {ab=2, a=2, b=2} System.out.println(collect4); Long collect = list.stream().collect(Collectors.counting()); // Result: 6 System.out.println(collect); List<Integer> list1 = Arrays.asList(1.3.5.7.9.11); Integer collect5 = list1.stream().collect(Collectors.maxBy((a, b) -> a.compareTo(b))).orElse(null); System.out.println(collect5); // Result: 11 System.out.println(collect5); String collect6 = list1.stream().collect(Collectors.minBy((a, b) -> a.compareTo(b))).orElse(null); // Result: 1 System.out.println(collect6); List<String> list2 = Arrays.asList("2"."3"."5"); IntSummaryStatistics summaryStatistics = list2.stream().collect(Collectors.summarizingInt(x -> Integer.parseInt(x))); long sum = summaryStatistics.getSum(); // Result: 10 System.out.println(sum); Double collect7 = list2.stream().collect(Collectors.averagingInt(x -> Integer.parseInt(x))); // Result: 3.333333333335 System.out.println(collect7); List<User> userList = new ArrayList<User>() {{ add(new User("jack".23)); add(new User("james".30)); add(new User("curry".28)); }}; List<String> collect8 = userList.stream().collect(Collectors.mapping(User::getName, Collectors.toList())); //[jack, james, curry] System.out.println(collect8); Copy the code
3. find
-
FindFirst: Finds the first element and returns type Optional
-
FindAny: Generally returns the first element, of type Optional, but is not guaranteed to be the first in parallel cases
List<String> lst1 = Arrays.asList("Jhonny"."David"."Jack"."Duke"."Jill"."Dany"."Julia"."Jenish"."Divya"); List<String> lst2 = Arrays.asList("Jhonny"."David"."Jack"."Duke"."Jill"."Dany"."Julia"."Jenish"."Divya"); Optional<String> findFirst = lst1.parallelStream().filter(s -> s.startsWith("D")).findFirst(); Optional<String> fidnAny = lst2.parallelStream().filter(s -> s.startsWith("J")).findAny(); System.out.println(findFirst.get()); // Always print David System.out.println(fidnAny.get()); // Will randomly print Jack/Jill/Julia Copy the code
4. match
-
AllMatch: Returns Boolean if all elements meet the criteria
-
AnyMatch: Returns Boolean if any element meets the condition
-
NoneMatch: All elements do not meet the criteria, return Boolean
List<Integer> list = Arrays.asList(2.3.5.7); boolean allMatch = list.stream().allMatch(x -> x > 1); // Result: true System.out.println(allMatch); boolean allMatch2 = list.stream().allMatch(x -> x > 2); // Result: false System.out.println(allMatch2); boolean anyMatch = list.stream().anyMatch(x -> x > 2); // Result: true System.out.println(anyMatch); boolean noneMatch1 = list.stream().noneMatch(x -> x > 5); // Result: false System.out.println(noneMatch1); boolean noneMatch2 = list.stream().noneMatch(x -> x > 7); // Result: true System.out.println(noneMatch2); Copy the code
5. count
-
Count quantities, returning long, similar to the size() method of the collection
List<String> list = Arrays.asList("a"."b"."ab"); long count = list.stream().count(); // Result: 3 System.out.println(count); Copy the code
6. The Max and min
-
Max: Gets the maximum value. Returns the Optional type
-
Min: Gets the minimum value and returns the Optional type
List<Integer> list = Arrays.asList(2.3.5.7); Optional<Integer> max = list.stream().max((a, b) -> a.compareTo(b)); // Result: 7 System.out.println(max.get()); Optional<Integer> min = list.stream().min((a, b) -> a.compareTo(b)); // Result: 2 System.out.println(min.get()); Copy the code
7. reduce
-
Specification operation, which specifies the entire data stream into a single value
-
Two parameters: the initial value of the loop calculation, calculation accumulator
-
Count, Max, and min are implemented using reduce
List<Integer> list = Arrays.asList(2.3.5.7); Integer sum1 = list.stream().reduce(0, Integer::sum); // Result: 17 System.out.println(sum1); Optional<Integer> reduce = list.stream().reduce((a, b) -> a + b); // Result: 17 System.out.println(reduce.get()); Integer max = list.stream().reduce(0, Integer::max); // Result: 7 System.out.println(max); Integer min = list.stream().reduce(0, Integer::min); // Result: 0 System.out.println(min); Optional<Integer> reduce1 = list.stream().reduce((a, b) -> a > b ? b : a); / / 2 System.out.println(reduce1.get()); Copy the code
8. toArray
-
Array operation to convert a stream of data into an array
List<String> list = Arrays.asList("a"."b"."ab"); String[] strings = list.stream().toArray(String[]::new); // Result: A, B, ab for (int i = 0; i < strings.length; i++) { System.out.print(strings[i]+""); } Copy the code
9. concat
-
Merge two streams into one
Stream<String> streamA = Stream.of("Zhang Wuji"); Stream<String> streamB = Stream.of("Zhang Cuishan"); Stream<String> result = Stream.concat(streamA, streamB); Copy the code