当前位置:网站首页>[list to map] collectors Tomap syntax sharing (case practice)
[list to map] collectors Tomap syntax sharing (case practice)
2022-07-03 15:55:00 【Chen Xi should work hard】
【 Chen Xi has to work hard 】:hello Hello, I'm Chen Xi , I'm glad you came to read , Nickname is the hope that you can constantly improve , Moving forward to good programmers !
The blog comes from the project and the summary of the problems encountered in programming , Occasionally there are books to share , I'll keep updating Java front end 、 backstage 、 database 、 Project cases and other related knowledge points summary , Thank you for your reading and attention , I hope my blog can help more people , Share and gain new knowledge , Make progress together !
We quarryers , The heart of a cathedral , I wish you all to go in your love …
List of articles
One 、 First time to know Collectors.toMap
In the real business scenario, there are many collections map The operation of , Let's study together today Collectors.toMap Related use
Create a house The object of
@Data
public class House {
private Integer id; //id
private Integer ownerid; // Home owner No
private String housename; // Family name
private String address; // Home address
}
Analog data
/** * @description: List turn Map operation * @author: Chen Xi has to work hard * @create: 2021-09-11 12:57 */
public class ListToMap {
public static void main(String[] args) {
House house = new House(1,1," Chen Xi "," Beijing haidian ");
House house1 = new House(2,2," Chen Xi has to work hard "," Wuhan, Hubei ");
House house2 = new House(3,3," Chen Xiaoxi "," Hangzhou, Zhejiang ");
ArrayList<House> houses = new ArrayList<>();
houses.add(house);
houses.add(house1);
houses.add(house2);
// In actual projects, we often use List turn Map operation -> It used to be for Operation of the cycle , Now you can learn the following methods Collectors.toMap
/** * Let's collect two separate attributes for each object in the collection */
Map<String, String> mapHouse = houses.stream().collect(Collectors.toMap(House::getHousename, House::getAddress));
System.out.println(mapHouse);
//{ Chen Xi has to work hard = Wuhan, Hubei , Chen Xiaoxi = Hangzhou, Zhejiang , Chen Xi = Beijing haidian }
/** * The data types of the attributes before and after should correspond to Collect business data with unique representation in general time business */
Map<Integer, String> map = houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename));
System.out.println(map);
//{1= Chen Xi , 2= Chen Xi has to work hard , 3= Chen Xiaoxi }
/** * Collect the attributes and the object itself */
Map<Integer, House> houseMap = houses.stream().collect(Collectors.toMap(House::getOwnerid, o -> o));
Map<Integer, House> houseMap1 = houses.stream().collect(Collectors.toMap(House::getOwnerid, Function.identity()));
System.out.println(houseMap);
/** * {1=House{id=1, ownerid=1, housename=' Chen Xi ', address=' Beijing haidian '}, * 2=House{id=2, ownerid=2, housename=' Chen Xi has to work hard ', address=' Wuhan, Hubei '}, * 3=House{id=3, ownerid=3, housename=' Chen Xiaoxi ', address=' Hangzhou, Zhejiang '}} */
// Business scenario : Generally, it will be based on the specific key value Take specific objects
System.out.println(houseMap.get(1));
//House{id=1, ownerid=1, housename=' Chen Xi ', address=' Beijing haidian '}
// The effect here is the same as houseMap
System.out.println(houseMap1);
/** * {1=House{id=1, ownerid=1, housename=' Chen Xi ', address=' Beijing haidian '}, * 2=House{id=2, ownerid=2, housename=' Chen Xi has to work hard ', address=' Wuhan, Hubei '}, * 3=House{id=3, ownerid=3, housename=' Chen Xiaoxi ', address=' Hangzhou, Zhejiang '}} */
}
}
Output effect : ditto 
You can practice common operations
houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename));
Learn grammar in detail : uncover System.out::println The veil of mystery
Two 、 thorough Collectors.toMap
Collectors.toMap There are three ways to overload :
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper);
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction);
toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier);
The meanings of the parameters are :
keyMapper:Key The mapping function of
valueMapper:Value The mapping function of
mergeFunction: When Key When the conflict , The merge method called
mapSupplier:Map Constructors , When you need to return a specific Map When using
The most business scenarios are map The key of is a unique identifier , The value is the object itself !
If you want to get Map Of value For the object itself , It can be written like this
/** * Collect the attributes and the object itself */
Map<Integer, House> houseMap = houses.stream().collect(Collectors.toMap(House::getOwnerid, o -> o));
Map<Integer, House> houseMap1 = houses.stream().collect(Collectors.toMap(House::getOwnerid, Function.identity()));
common java.lang.IllegalStateException: Duplicate key Problem handling 
The online business code appears Duplicate Key It's abnormal , It affects the business logic , Look at the code that throws the exception
Exception in thread "main" java.lang.IllegalStateException: Duplicate key Chen Xi
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1254)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.example.cwgl.ListToMap.main(ListToMap.java:28)
terms of settlement : When duplicate occurs , Take the front value Value , Or take what you put in the back value value , Then the previous value value
houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename,(v1,v2)->v2));
houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename,(v1,v2)->v1));
The implementation effect is as follows : Don't complain , The normal value covers 
There are many ways to deal with the operation of results , Such as splicing
houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename,(v1,v2)->v1+v2));
Execution effect
{
1= Chen Xi, Chen Xiao Xi , 2= Chen Xi has to work hard }
The specific practice is to operate the data according to the specific business
Record Chen Xi's first 200 blog ! Clear objectives , perform , reflection , Refinement ! Become an excellent programmer as soon as possible !
Thank you very much for reading here , If this article helps you , I hope I can leave your praise Focus on ️ Share Leaving a message. thanks!!!
2021 year 9 month 12 Japan 17:56:48 May you go to your love !
边栏推荐
- App mobile terminal test [5] file writing and reading
- Automatic generation of client code from flask server code -- Introduction to flask native stubs Library
- Win32 create window and button (lightweight)
- Visual host system design and development (Halcon WinForm)
- Under VC, Unicode and ANSI are converted to each other, cstringw and std:: string are converted to each other
- “用Android复刻Apple产品UI”(3)—优雅的数据统计图表
- C语言刷题~Leetcode与牛客网简单题
- Unity function - unity offline document download and use
- 【OpenCV 例程200篇】217. 鼠标交互获取多边形区域(ROI)
- Custom annotation
猜你喜欢

Break through 1million, sword finger 2million!

Mongodb installation and basic operation

秒杀系统2-Redis解决分布式Session问题

Distributed task scheduling XXL job
![App mobile terminal test [3] ADB command](/img/f1/4bff6e66b77d0f867bf7237019e982.png)
App mobile terminal test [3] ADB command

Visual host system design and development (Halcon WinForm)

Unityshader - materialcapture material capture effect (Emerald axe)

Salary 3000, monthly income 40000 by "video editing": people who can make money never rely on hard work!

Project -- high concurrency memory pool

使用AUR下载并安装常用程序
随机推荐
App mobile terminal test [4] APK operation
A Fei's expectation
App mobile terminal test [3] ADB command
软件安装信息、系统服务在注册表中的位置
How to use annotations such as @notnull to verify and handle global exceptions
Persisting in output requires continuous learning
Visual upper system design and development (Halcon WinForm) -3 Image control
阿飞的期望
Reflection on some things
需要知道的字符串函数
Popular understanding of gradient descent
Distributed task scheduling XXL job
秒杀系统2-Redis解决分布式Session问题
Three dimensional reconstruction of deep learning
Detailed explanation of four modes of distributed transaction (Seata)
QT use qzxing to generate QR code
[系统安全] 四十三.Powershell恶意代码检测系列 (5)抽象语法树自动提取万字详解
Microservice API gateway zuul
Visual upper system design and development (Halcon WinForm) -5 camera
Reading notes of "micro service design" (Part 2)