当前位置:网站首页>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());
}
}
边栏推荐
- Skill combing [email protected] somatosensory manipulator
- 透過華為軍團看科技之變(五):智慧園區
- The intelligent DNA molecular nano robot model is coming
- R language plot visualization: use plot to visualize the prediction confidence of the multi classification model, the prediction confidence of each data point of the model in the 2D grid, and the conf
- CVPR 2022 | 清华&字节&京东提出BrT:用于视觉和点云3D目标检测的桥接Transformer
- LVGL 8.2 Simple Drop down list
- CSDN博客运营团队2022年H1总结
- Getting started with X86 - take over bare metal control
- Foresniffer tutorial: extracting data
- Viewing technological changes through Huawei Corps (V): smart Park
猜你喜欢
Mysql database foundation: constraint and identification columns
Apple's 5g chip was revealed to have failed in research and development, and the QQ password bug caused heated discussion. Wei Lai responded to the short selling rumors. Today, more big news is here
机器学习面试准备(一)KNN
File sharing server
Migrate full RT thread to gd32f4xx (detailed)
微信推出图片大爆炸功能;苹果自研 5G 芯片或已失败;微软解决导致 Edge 停止响应的 bug|极客头条...
pytorch 筆記 torch.nn.BatchNorm1d
I found a wave of "alchemy artifact" in the goose factory. The developer should pack it quickly
ArcGIS Pro scripting tool (6) -- repairing CAD layer data sources
我在鹅厂淘到了一波“炼丹神器”,开发者快打包
随机推荐
ionic4 ion-reorder-group组件拖拽改变item顺序
六月集训(第30天) —— 拓扑排序
Skill combing [email protected] somatosensory manipulator
程序员需知的 59 个网站
Mysql database foundation: constraint and identification columns
Skill combing [email protected] voice module +stm32+nfc
LVGL 8.2 re-coloring
同事的接口文档我每次看着就头大,毛病多多。。。
Memory escape analysis
CVPR 2022 | 清华&字节&京东提出BrT:用于视觉和点云3D目标检测的桥接Transformer
LVGL 8.2 menu from a drop-down list
How can the sports app keep the end-to-side background alive to make the sports record more complete?
Skill sorting [email protected]+ Alibaba cloud +nbiot+dht11+bh1750+ soil moisture sensor +oled
转卡通学习笔记
Kernel linked list (general linked list) "list.h" simple version and individual comments
Matplotlib notes: contour & Contour
安徽《合肥市装配式建筑施工图审查设计深度要求》印发;河北衡水市调整装配式建筑预售许可标准
MySQL导出sql脚本文件
My in-depth remote office experience | community essay solicitation
Pytorch notes torch nn. BatchNorm1d