当前位置:网站首页>Collectors. Tomap application
Collectors. Tomap application
2022-06-30 10:48:00 【gqltt】
Collectors.toMap Introduce
There are many in real business scenarios aggregate turn map The operation of , for example
@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
*/
public class ListToMap {
public static void main(String[] args) {
House house = new House(1,1,"aa"," Beijing haidian ");
House house1 = new House(2,2,"bb"," Wuhan, Hubei ");
House house2 = new House(3,3,"cc"," 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);
//{aa= Wuhan, Hubei , bb= Hangzhou, Zhejiang , cc= 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=aa, 2=bb, 3=cc}
/**
* 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='aa', address=' Beijing haidian '},
* 2=House{id=2, ownerid=2, housename='bb', address=' Wuhan, Hubei '},
* 3=House{id=3, ownerid=3, housename='cc', 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='aa', address=' Beijing haidian '}
// The effect here is the same as houseMap
System.out.println(houseMap1);
/**
* {1=House{id=1, ownerid=1, housename='aa', address=' Beijing haidian '},
* 2=House{id=2, ownerid=2, housename='bb', address=' Wuhan, Hubei '},
* 3=House{id=3, ownerid=3, housename='cc', address=' Hangzhou, Zhejiang '}}
*/
}
}
You can practice common operations
houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename));
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
We put the test data House house = new House(1,1,“aa”,“ Beijing haidian ”);
House house1 = new House(2,2,“bb”,“ Wuhan, Hubei ”);
House house2 = new House(3,3,“cc”,“ Hangzhou, Zhejiang ”);
house2 It is amended as follows : House house2 = new House(3,1,“cc”,“ Hangzhou, Zhejiang ”);
such Ownerid Will repeat
When we execute the following code :houses.stream().collect(Collectors.toMap(House::getOwnerid, House::getHousename);
Will make mistakes ,java.lang.IllegalStateException: Duplicate key
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 aa
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));
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));
The specific practice is to operate the data according to the specific business
List Count the number of duplicates
final String path = "F:/AppData/API-url.txt";
final List<String> list = BlockIOUtil.readLines("file:" + path);
Map<String, Integer> map =
list.stream().collect(Collectors.toMap(it -> it, it -> 1, (val1, val2) -> val1 + 1));
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue() != null && entry.getValue() > 1) {
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}边栏推荐
- Machine learning interview preparation (I) KNN
- Review of mathematical knowledge: curve integral of the second type
- Gd32 RT thread PWM drive function
- MySQL导出sql脚本文件
- Unity Shader - 踩坑 - BRP 管线中的 depth texture 的精度问题(暂无解决方案,推荐换 URP)
- Auto SEG loss: automatic loss function design
- Migrate full RT thread to gd32f4xx (detailed)
- 潘多拉 IOT 开发板学习(HAL 库)—— 实验1 跑马灯(RGB)实验(学习笔记)
- LVGL 8.2 Image styling and offset
- Kernel linked list (general linked list) "list.h" simple version and individual comments
猜你喜欢

Android 开发面试真题进阶版(附答案解析)

智能DNA分子纳米机器人模型来了

Every time I look at my colleagues' interface documents, I get confused and have a lot of problems...

mysql数据库基础:约束、标识列

苹果高管公然“开怼”:三星抄袭 iPhone,只加了个大屏

Dow Jones Industrial Average

mysql数据库基础:存储过程和函数

Retest the cloud native database performance: polardb is still the strongest, while tdsql-c and gaussdb have little change

pytorch 笔记 torch.nn.BatchNorm1d
[email protected] control a dog's running on OLED"/>Skill combing [email protected] control a dog's running on OLED
随机推荐
7 大轻量易用的工具,给开发者减压提效,助力企业敏捷上云 | Techo Day 精彩回顾...
ArcGIS Pro scripting tool (5) - delete duplicates after sorting
Foresniffer tutorial: extracting data
数学知识复习:第二型曲线积分
LVGL 8.2 Image styling and offset
运动App如何实现端侧后台保活,让运动记录更完整?
LVGL 8.2 Image
Google 辟谣放弃 TensorFlow,它还活着!
程序员需知的 59 个网站
吴恩达2022机器学习专项课测评来了!
sCrypt 中的 ECDSA 签名验证
Getting started with X86 - take over bare metal control
& and - > priority
mysql数据库基础:存储过程和函数
LVGL 8.2 re-coloring
最新SCI影响因子公布:国产期刊最高破46分!网友:算是把IF玩明白了
腾讯云数据库工程师能力认证重磅推出,各界共话人才培养难题
LVGL 8.2 menu from a drop-down list
Agile Development: super easy to use bucket estimation system
go-zero微服务实战系列(八、如何处理每秒上万次的下单请求)