当前位置:网站首页>[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移动端测试【5】文件的写入、读取
- Detailed explanation of four modes of distributed transaction (Seata)
- Visual upper system design and development (Halcon WinForm) -6 Nodes and grids
- Detailed pointer advanced 2
- Summary of JVM knowledge points
- Popular understanding of ovo and ovr
- C language brush questions ~leetcode and simple questions of niuke.com
- About text selection in web pages and counting the length of selected text
- Intelij idea efficient skills (III)
- The difference between mutually exclusive objects and critical areas
猜你喜欢

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

秒杀系统1-登录功能

求字符串函数和长度不受限制的字符串函数的详解

嵌入式开发:避免开源软件的7个理由

Find mapping relationship

Intelij idea efficient skills (III)

String functions that you need to know

Secsha system 1- login function

Please be prepared to lose your job at any time within 3 years?

CString的GetBuffer和ReleaseBuffer使用说明
随机推荐
Redis high availability and persistence
Project -- high concurrency memory pool
Detailed pointer advanced 2
整形和浮点型是如何在内存中的存储
Shell script import and export data
Reflection on some things
【Proteus仿真】8×8LED点阵屏仿电梯数字滚动显示
突破100万,剑指200万!
Mongodb installation and basic operation
Download and install common programs using AUR
Three dimensional reconstruction of deep learning
使用AUR下载并安装常用程序
Please be prepared to lose your job at any time within 3 years?
嵌入式开发:避免开源软件的7个理由
Atlas atlas torque gun USB communication tutorial based on mtcom
利用MySQL中的乐观锁和悲观锁实现分布式锁
"Remake Apple product UI with Android" (2) -- silky Appstore card transition animation
Microservice - fuse hystrix
QT common sentence notes
CString的GetBuffer和ReleaseBuffer使用说明