当前位置:网站首页>[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);
}
边栏推荐
- 别再用 offset 和 limit 分页了,性能太差!
- 【ELM分类】基于核极限学习机和极限学习机实现UCI数据集分类附matlab代码
- Using pytorch's tensorboard visual deep learning indicators | pytorch series (25)
- Pytest the best testing framework
- 数据湖:各模块组件
- [wechat applet development (V)] the interface is intelligently configured according to the official version of the experience version of the development version
- Ci/cd from hardware programming to software platform
- 分布式 session 的4个解决方案,你觉得哪个最好?
- Confusion matrix in CNN | pytorch series (XXIII)
- Ah Han's story
猜你喜欢

PS simple to use

Data Lake: database data migration tool sqoop
![[wechat applet development (VI)] draw the circular progress bar of the music player](/img/eb/9ce5d196970a6d6a887bf3e1d742ee.png)
[wechat applet development (VI)] draw the circular progress bar of the music player

Actual case of ROS communication

Data Lake: flume, a massive log collection engine

First knowledge of C language -- structure, branch and loop statements
[email protected] Annotation usage"/>[email protected] Annotation usage

Consolidate the data foundation in the data center

分布式 session 的4个解决方案,你觉得哪个最好?

数据中台建设(三):数据中台架构介绍
随机推荐
Consolidate the data foundation in the data center
阿憨的故事
[wechat applet development (V)] the interface is intelligently configured according to the official version of the experience version of the development version
Introduction to the reduce() function in JS
Using pytorch's tensorboard visual deep learning indicators | pytorch series (25)
CNN训练循环重构——超参数测试 | PyTorch系列(二十八)
Canvas from getting started to persuading friends to give up (graphic version)
Canonical Address
openGauss源代码,用什么IDE工具管理、编辑、调试?
一次跨域问题的记录
Chapter III queue
tfx airflow 使用体验
Docker高级篇-Docker容器内Redis集群配置
Data Lake: flume, a massive log collection engine
Center Based 3D object detection and tracking (centerpoint) paper notes
Docker advanced -redis cluster configuration in docker container
[red team] att & CK - file hiding
注意,这些地区不能参加7月NPDP考试
vscode debug显示多列数据
Why is there no unified quotation for third-party testing fees of software products?