当前位置:网站首页>[stream] basic knowledge of stream
[stream] basic knowledge of stream
2022-07-28 03:02:00 【Zhang Yanwei_ Laura】
What is?
Java8 There are two most important changes . The first is Lambda expression ; The other one is Stream API(java.util.stream.*).
Stream yes Java8 , which deals with key abstractions of collections , It specifies what you want to do with the collection , You can perform very complex lookups 、 Operations such as filtering and mapping data . Use Stream API Operates on the collection data , It's kind of like using SQL Executed database query . You can also use Stream API To execute operations in parallel . In short , Stream API Provides an efficient and easy-to-use way to process data .
flow (Stream) What is it ?
It's the data channel , Used to manipulate data sources ( aggregate 、 Array etc. ) The generated sequence of elements .“ Collections are about data , Flow is about computation !”
Be careful :
①Stream You don't store elements by yourself .
②Stream The source object does not change . contrary , They will return a new Stream.
③Stream The operation is delayed . This means that they wait until they need results to execute .
Why use
Simplify the amount of code
Use steps
establish Stream– Acquisition data source
A data source ( Such as : aggregate 、 Array ), Get a stream
Intermediate operation – Data processing
An intermediate operation chain , Process the data from the data source
Termination operation ( Terminal operation )– Data integration
A termination operation , Perform intermediate operation chain , And produce results 
Create stream
Java8 Medium Collection The interface is extended , There are two ways to get the stream :
default Stream stream() : Returns a sequence stream
default Stream parallelStream() : Return a parallel stream
Create a stream from an array
Java8 Medium Arrays Static method of stream() You can get the array stream :
static Stream stream(T[] array): Back to a stream
Heavy duty form , Can handle arrays of corresponding basic types :
public static IntStream stream(int[] array)
public static LongStream stream(long[] array)
public static DoubleStream stream(double[] array)
Create stream from value
You can use static methods Stream.of(), Create a stream by displaying values . It can take any number of parameters .
public static Stream of(T… values) : Back to a stream
Create a stream from a function : Create an infinite flow
You can use static methods Stream.iterate() and Stream.generate(), Create an infinite flow .
iteration
public static Stream iterate(final T seed, final UnaryOperator f)
Generate
public static Stream generate(Supplier s) :
Code implementation
@Test
public void test1(){
//1. Collection Two methods are provided stream() And parallelStream()
List<String> list = new ArrayList<>();
// Get a sequence stream
Stream<String> stream = list.stream();
// Get a parallel stream
Stream<String> parallelStream = list.parallelStream();
//2. Create a stream from an array , adopt Arrays Medium stream() Get an array stream
Integer[] nums = new Integer[10];
Stream<Integer> stream1 = Arrays.stream(nums);
//3. Create stream from value , adopt Stream Static methods in class of()
Stream<Integer> stream2 = Stream.of(1,2,3,4,5,6);
//4. Create a stream from a function , Create an infinite flow
// Use static methods Stream.iterate() and Stream.generate()
// iteration
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 2).limit(10);
stream3.forEach(System.out::println);
// Generate
Stream<Double> stream4 = Stream.generate(Math::random).limit(2);
stream4.forEach(System.out::println);
}
stream Intermediate operation
Multiple intermediate operations can be connected to form a pipeline , Unless termination is triggered on the pipeline , Otherwise, the intermediate operation will not perform any processing ! When the operation is terminated, all of them are handled at one time , be called “ Lazy evaluation ”.
Screening and slicing

//2. Intermediate operation
List<Employee> emps = Arrays.asList(
new Employee(102, " Li Si ", 59, 6666.66),
new Employee(101, " Zhang San ", 18, 9999.99),
new Employee(103, " Wang Wu ", 28, 3333.33),
new Employee(104, " Zhao Liu ", 8, 7777.77),
new Employee(104, " Zhao Liu ", 8, 7777.77),
new Employee(104, " Zhao Liu ", 8, 7777.77),
new Employee(105, " Panax notoginseng ", 38, 5555.55)
);
filter
/* Screening and slicing filter—— receive Lambda , Exclude certain elements from the stream . limit—— Truncation stream , Keep its elements to a given number . skip(n) —— Skip the element , Back to a throw away before n A stream of elements . If there are not enough elements in the stream n individual , It returns an empty stream . And limit(n) complementary distinct—— Screening , Of the elements generated by the flow hashCode() and equals() Remove duplicate elements */
// Internal iteration : Iterative operations Stream API Internal finish
@Test
public void test2(){
// All intermediate operations do not do any processing
Stream<Employee> stream = emps.stream()
.filter((e) -> {
System.out.println(" Test the intermediate operation ");
return e.getAge() <= 35;
});
// Only when the operation is terminated , All intermediate operations will be executed at one time , be called “ Lazy evaluation ”
stream.forEach(System.out::println);
}
// External iteration
@Test
public void test3(){
Iterator<Employee> it = emps.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
limit
@Test
public void test4(){
// emps.stream()
// .filter((e) -> {
// System.out.println(" A short circuit !"); // && ||
// return e.getSalary() >= 5000;
// }).limit(3)
// .forEach(System.out::println);
emps.stream()
.filter((e)->e.getSalary()>5000)
.limit(2)
.forEach(System.out::println);
}
skip
@Test
public void test5(){
emps.parallelStream()
.filter((e) -> e.getSalary() >= 5000)
.skip(2)
.forEach(System.out::println);
}
distinct
@Test
public void test6(){
emps.stream()
.distinct()
.forEach(System.out::println);
}
mapping
map—— receive Lambda , Convert elements to other forms or extract information . Receive a function as an argument , This function is applied to each element , And map it to a new element .
flatMap—— Receive a function as an argument , Replace each value in the stream with another stream , Then connect all streams into one stream 
/* mapping map—— receive Lambda , Convert elements to other forms or extract information . Receive a function as an argument , This function is applied to each element , And map it to a new element . flatMap—— Receive a function as an argument , Replace each value in the stream with another stream , Then connect all streams into one stream */
List<String> strList = Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee");
// The first one is
Stream<String> stream = strList.stream().map(String::toUpperCase);
stream.forEach(System.out::println);
// The second kind
strList.stream().map((s)->s.toUpperCase()).forEach(System.out::println);
// The third kind of
strList.stream().map(Employee::getName).forEach(System.out::println);
flatMap
public static Stream<Character> filterCharacter(String str){
List<Character> list = new ArrayList<>();
for (Character ch : str.toCharArray()) {
list.add(ch);
}
return list.stream();
}
// Generate a single stream
Stream<Stream<Character>> stream2 = strList.stream()
.map(TestStreamAPI1::filterCharacter);
stream2.forEach((sm) -> {
sm.forEach(System.out::println);
});
System.out.println("---------------------------------------------");
// Integrate individual streams , Generate a stream
Stream<Character> stream3 = strList.stream()
.flatMap(TestStreamAPI1::filterCharacter);//TestStreamAPI1 The name of the class , Get the methods in the class filterCharacter
stream3.forEach(System.out::println);
Sort

/* sorted()—— Natural ordering (Comparable) sorted(Comparator com)—— Custom sort */
@Test
public void test2(){
emps.stream()
.map(Employee::getName)
.sorted()
.forEach(System.out::println);
System.out.println("------------------------------------");
// Sort by age , Those with the same age are sorted by name
emps.stream()
.sorted((x, y) -> {
if(x.getAge() == y.getAge()){
return x.getName().compareTo(y.getName());
}else{
return Integer.compare(x.getAge(), y.getAge());
}
}).forEach(System.out::println);
}
stream Termination of
Terminal operations generate results from the pipeline of the stream . The result can be anything that's not streaming
value , for example :List、Integer, Even void .
Find and match


/* allMatch—— Check to see if all elements match anyMatch—— Check that at least one element matches noneMatch—— Check if there are no matching elements 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 */
@Test
public void test1(){
// Check that all elements match
boolean bl = emps.stream()
.allMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(bl);
System.out.println("--------------------------------");
// Match at least one element
boolean bl1 = emps.stream()
.anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(bl1);
System.out.println("--------------------------------");
// Not all elements match
boolean bl2 = emps.stream()
.noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(bl2);
System.out.println("--------------------------------");
// Returns the first element
Optional<Employee> op = emps.stream()
.sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(op.get());
System.out.println("--------------------------------");
// Returns any element in the current stream
Optional<Employee> op2 = emps.parallelStream()
.filter((e) -> e.getStatus().equals(Status.FREE))
.findAny();
System.out.println(op2.get());
// Returns the total number of elements in the stream
long count = emps.stream()
.filter((e) -> e.getStatus().equals(Status.FREE))
.count();
System.out.println(count);
System.out.println("--------------------------------");
// Maximum
Optional<Double> op = emps.stream()
.map(Employee::getSalary)
.max(Double::compare);
System.out.println(op.get());
System.out.println("--------------------------------");
// minimum value
Optional<Employee> op2 = emps.stream()
.min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(op2.get());
}
reduction

remarks :map and reduce The connection of is usually called map-reduce Pattern , because Google Use it
To search the web .
/* reduction reduce(T identity, BinaryOperator) / reduce(BinaryOperator) —— You can combine elements of the stream over and over again , Get a value . */
@Test
public void test1(){
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer sum = list.stream()
.reduce(0, (x, y) -> x + y);
//reduce( Starting value , Numerical processing logic )
System.out.println(sum);
System.out.println("----------------------------------------");
// It may be control , Avoid null pointers
Optional<Double> op = emps.stream()
.map(Employee::getSalary)
.reduce(Double::sum);
System.out.println(op.get());
}
collect

Collector The implementation of the methods in the interface determines how collection operations are performed on the stream ( If you collect List、Set、Map). however Collectors Utility classes provide many static methods , You can easily create common collector instances , The specific methods and examples are as follows :
collectors Tool class :

// collect
// collect—— Convert streams to other forms . Receive one Collector Interface implementation , For giving Stream The method of summarizing elements in
@Test
public void test3(){
List<String> list = emps.stream()
.map(Employee::getName)
.collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("----------------------------------");
Set<String> set = emps.stream()
.map(Employee::getName)
.collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println("----------------------------------");
HashSet<String> hs = emps.stream()
.map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);
}
@Test
public void test4(){
// Maximum
Optional<Double> max = emps.stream()
.map(Employee::getSalary)
.collect(Collectors.maxBy(Double::compare));
System.out.println(max.get());
System.out.println("----------------------------------");
// minimum value
Optional<Employee> op = emps.stream()
.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(op.get());
System.out.println("----------------------------------");
// The sum of the
Double sum = emps.stream()
.collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
System.out.println("----------------------------------");
// Average
Double avg = emps.stream()
.collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
System.out.println("----------------------------------");
// total
Long count = emps.stream()
.collect(Collectors.counting());
System.out.println(count);
System.out.println("--------------------------------------------");
// Return to a collection , Various values can be taken
DoubleSummaryStatistics dss = emps.stream()
.collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(dss.getMax());
System.out.println(dss.getCount());
System.out.println(dss.getMin());
System.out.println(dss.getSum());
System.out.println(dss.getAverage());
}
// grouping
@Test
public void test5(){
Map<Status, List<Employee>> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);
}
// Multi level grouping
@Test
public void test6(){
Map<Status, Map<String, List<Employee>>> map = emps.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if(e.getAge() >= 60)
return " The elderly ";
else if(e.getAge() >= 35)
return " middle-aged ";
else
return " adult ";
})));
System.out.println(map);
}
// Partition
// TRUE and false The difference between , A satisfied area, a dissatisfied area
@Test
public void test7(){
Map<Boolean, List<Employee>> map = emps.stream()
.collect(Collectors.partitioningBy((e) -> e.getSalary() >= 5000));
System.out.println(map);
}
// Connection string
// Generate “---- Zhang San , Li Si , Wang Wu ----”
@Test
public void test8(){
String str = emps.stream()
.map(Employee::getName)
.collect(Collectors.joining("," , "----", "----"));
System.out.println(str);
}
边栏推荐
- 微服务架构统一安全认证设计与实践
- Newline required at end of file but not found.
- 小程序已获取数据库合集中的总记录、用户位置,怎么用Aggregate.geoNear将经纬度由近到远排列?
- 【TA-霜狼_may-《百人计划》】图形3.5 Early-z 和 Z-prepass
- style=“width: ___“ VS width=“___“
- CNN training cycle reconstruction - hyperparametric test | pytorch series (XXVIII)
- @The function of valid (cascade verification) and the explanation of common constraint annotations
- 【信号去噪】基于卡尔曼滤波实现信号去噪附matlab代码
- 42.js -- precompiled
- Actual case of ROS communication
猜你喜欢

app 自动化 环境搭建(一)

PS simple to use

On the problem that sqli labs single quotation marks do not report errors

Data Lake: database data migration tool sqoop

CNN循环训练的解释 | PyTorch系列(二十二)

Introduction to the reduce() function in JS

ROS的调试经验

How do gateways and chirpstacks in lorawan communicate? UDP? GRPC? MQTT?

Using pytorch's tensorboard visual deep learning indicators | pytorch series (25)

Redis AOF log persistence
随机推荐
ORACLE BASICFILE LOB字段空间回收SHRINK SPACE的疑惑
数据中台建设(三):数据中台架构介绍
【TA-霜狼_may-《百人计划》】图形3.5 Early-z 和 Z-prepass
Explanation of CNN circular training | pytorch series (XXII)
[TA frost wolf \u may - hundred people plan] Figure 3.7 TP (d) r architecture of mobile terminal
[image defogging] image defogging based on dark channel and non-mean filtering with matlab code
Day 19 of leetcode
Newline required at end of file but not found.
Data Lake: each module component
Data Lake: database data migration tool sqoop
unordered_ The hash function of map and the storage mode of hash bucket
智能工业设计软件公司天洑C轮数亿元融资
NPDP考生!7月31号考试要求在这里看!
Is the interface that can be seen everywhere in the program really useful? Is it really right?
数据湖:各模块组件
Skills in writing English IEEE papers
[email protected]注解使用
Why is there no unified quotation for third-party testing fees of software products?
牛客-TOP101-BM340
JS event object 2 e.charcode character code e.keycode key code box moves up, down, left and right