当前位置:网站首页>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());
}
}
边栏推荐
- Smith chart view of semi steel coaxial RF line and RF line matching calibration of network analyzer e5071c
- Foresniffer tutorial: extracting data
- The AOV function of R language was used for repeated measures ANOVA (one intra group factor and one inter group factor) and interaction Plot function and boxplot to visualize the interaction
- js常见问题
- LVGL 8.2 menu from a drop-down list
- MySQL从入门到精通50讲(三十二)-ScyllaDB生产环境集群搭建
- 微信推出图片大爆炸功能;苹果自研 5G 芯片或已失败;微软解决导致 Edge 停止响应的 bug|极客头条...
- Auto SEG loss: automatic loss function design
- Double-DQN笔记
- 59 websites programmers need to know
猜你喜欢
文件共享服务器
我在鹅厂淘到了一波“炼丹神器”,开发者快打包
scratch绘制正方形 电子学会图形化编程scratch等级考试二级真题和答案解析2022年6月
Remember the experience of an internship. It is necessary to go to the pit (I)
Overview of currency
Review of mathematical knowledge: curve integral of the second type
Auto Seg-Loss: 自动损失函数设计
同事的接口文档我每次看着就头大,毛病多多。。。
Migrate full RT thread to gd32f4xx (detailed)
ArcGIS Pro scripting tool (5) - delete duplicates after sorting
随机推荐
Skill sorting [email protected]+ Alibaba cloud +nbiot+dht11+bh1750+ soil moisture sensor +oled
CVPR 2022 | Tsinghua & bytek & JD put forward BRT: Bridging Transformer for vision and point cloud 3D target detection
Auto Seg-Loss: 自动损失函数设计
Didi open source agile test case management platform!
CP2112使用USB转IIC通信教学示例
The programmer was beaten.
Implementation of monitor program with assembly language
JS FAQs
[rust daily] the first rust monthly magazine on January 22, 2021 invites everyone to participate
Dow Jones Industrial Average
About Library (function library), dynamic library and static library
前嗅ForeSpider教程:抽取数据
深潜Kotlin协程(十八):冷热数据流
Machine learning interview preparation (I) KNN
Auto SEG loss: automatic loss function design
Memory escape analysis
技能梳理[email protected]體感機械臂
LVGL 8.2 Image
R语言plotly可视化:使用plotly可视化多分类模型的预测置信度、模型在2D网格中每个数据点预测的置信度、置信度定义为在某一点上最高分与其他类别得分之和之间的差值
超长干货 | Kubernetes命名空间详解