当前位置:网站首页>[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 !
边栏推荐
- nifi从入门到实战(保姆级教程)——flow
- The difference between RAR and zip files
- Nifi from introduction to practice (nanny level tutorial) - flow
- Introduction series of software reverse cracking (1) - common configurations and function windows of xdbg32/64
- Microservice sentinel flow control degradation
- Go language self-study series | golang switch statement
- Salary 3000, monthly income 40000 by "video editing": people who can make money never rely on hard work!
- "Remake Apple product UI with Android" (2) -- silky Appstore card transition animation
- Jmeter线程组功能介绍
- Download and install common programs using AUR
猜你喜欢
Detailed explanation of string function and string function with unlimited length
Srs4.0+obs studio+vlc3 (environment construction and basic use demonstration)
Secsha system 1- login function
深度学习之三维重建
《微服务设计》读书笔记(下)
【OpenCV 例程200篇】217. 鼠标交互获取多边形区域(ROI)
Please be prepared to lose your job at any time within 3 years?
QT use qzxing to generate QR code
Redis在Windows以及Linux系统下的安装
嵌入式开发:避免开源软件的7个理由
随机推荐
"Remake Apple product UI with Android" (2) -- silky Appstore card transition animation
Tensorflow realizes verification code recognition (III)
秒殺系統3-商品列錶和商品詳情
潘多拉 IOT 开发板学习(HAL 库)—— 实验5 外部中断实验(学习笔记)
Popular understanding of decision tree ID3
Digital image processing -- popular understanding of corrosion and expansion
VS2017通过IP调试驱动(双机调试)
Redis high availability and persistence
深度学习之三维重建
使用AUR下载并安装常用程序
How to use annotations such as @notnull to verify and handle global exceptions
Srs4.0+obs studio+vlc3 (environment construction and basic use demonstration)
[combinatorics] combinatorial identities (recursive combinatorial identities | sum of variable terms | simple combinatorial identities and | sum of variable terms | staggered sums of combinatorial ide
Location of software installation information and system services in the registry
Win32 create window and button (lightweight)
请做好3年内随时失业的准备?
秒杀系统2-Redis解决分布式Session问题
整形和浮点型是如何在内存中的存储
Pandora IOT development board learning (HAL Library) - Experiment 5 external interrupt experiment (learning notes)
Project -- high concurrency memory pool