当前位置:网站首页>[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);
}
边栏推荐
- Welcome to CSDN markdown editor Assad
- Gbase8s how to delete data in a table with a foreign key relationship
- New infrastructure helps the transformation and development of intelligent road transportation
- [email protected]注解使用
- Day 19 of leetcode
- Opengauss Developer Day 2022 sincerely invites you to visit the "database kernel SQL Engine sub forum" of Yunhe enmo
- unordered_ The hash function of map and the storage mode of hash bucket
- A 64 bit 8-stage pipelined adder based on FPGA
- Constant power wireless charging based on stm32
- Center-based 3D Object Detection and Tracking(基于中心的3D目标检测和跟踪 / CenterPoint)论文笔记
猜你喜欢

Center-based 3D Object Detection and Tracking(基于中心的3D目标检测和跟踪 / CenterPoint)论文笔记

Confusion matrix in CNN | pytorch series (XXIII)

Opengauss Developer Day 2022 sincerely invites you to visit the "database kernel SQL Engine sub forum" of Yunhe enmo

【信号去噪】基于卡尔曼滤波实现信号去噪附matlab代码

“29岁,普通功能测试,我是如何在一周内拿到5份Offer的?”

【微信小程序开发(六)】绘制音乐播放器环形进度条

app 自动化 环境搭建(一)

How do gateways and chirpstacks in lorawan communicate? UDP? GRPC? MQTT?
![Trivy [1] tool scanning application](/img/b1/c05949f9379fcde658da64f3a0157a.png)
Trivy [1] tool scanning application

微服务架构统一安全认证设计与实践
随机推荐
【信号处理】基于高阶统计量特征的通信系统中微弱信号检测附matlab代码
【ELM分类】基于核极限学习机和极限学习机实现UCI数据集分类附matlab代码
优炫数据库客户端如何认证
分布式事务——Senta(一)
【 图像去雾】基于暗通道和非均值滤波实现图像去雾附matlab代码
没法预测明天的涨跌
入职华为od一个月的感受
Email security report in the second quarter: email attacks have soared fourfold, and well-known brands have been used to gain trust
There is no way to predict the rise and fall of tomorrow
[acnoi2022] one step short
数据湖:海量日志采集引擎Flume
CNN循环训练的解释 | PyTorch系列(二十二)
使用PyTorch的TensorBoard-可视化深度学习指标 | PyTorch系列(二十五)
【红队】ATT&CK - 文件隐藏
Consolidate the data foundation in the data center
JS event object 2 e.charcode character code e.keycode key code box moves up, down, left and right
[QNX hypervisor 2.2 user manual]9.10 pass
How to simply realize the function of menu dragging and sorting
@The function of valid (cascade verification) and the explanation of common constraint annotations
[image hiding] digital image information hiding system based on DCT, DWT, LHA, LSB, including various attacks and performance parameters, with matlab code