当前位置:网站首页>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());
}
}边栏推荐
- SGD有多种改进的形式,为什么大多数论文中仍然用SGD?
- Skill combing [email protected] somatosensory manipulator
- pytorch 笔记 torch.nn.BatchNorm1d
- 05_Node js 文件管理模块 fs
- & and - > priority
- Foresniffer tutorial: extracting data
- R语言aov函数进行重复测量方差分析(Repeated measures ANOVA、其中一个组内因素和一个组间因素)、分别使用interaction.plot函数和boxplot对交互作用进行可视化
- ArrayList与顺序表
- Overview of currency
- Skill combing [email protected] intelligent instrument teaching aids based on 51 series single chip microcomputer
猜你喜欢

Anhui "requirements for design depth of Hefei fabricated building construction drawing review" was printed and distributed; Hebei Hengshui city adjusts the pre-sale license standard for prefabricated
[email protected]+adxl345+ Motor vibration + serial port output"/>Skill sorting [email protected]+adxl345+ Motor vibration + serial port output

我在鹅厂淘到了一波“炼丹神器”,开发者快打包

CVPR 2022 | Tsinghua & bytek & JD put forward BRT: Bridging Transformer for vision and point cloud 3D target detection

GeoffreyHinton:我的五十年深度学习生涯与研究心法

深潜Kotlin协程(十八):冷热数据流

19:00 p.m. tonight, knowledge empowerment phase 2 live broadcast - control panel interface design of openharmony smart home project

pytorch 笔记 torch.nn.BatchNorm1d

Pytorch Notebook. Nn. Batchnorm1d

Machine learning interview preparation (I) KNN
随机推荐
Gd32 RT thread PWM drive function
Viewing technological changes through Huawei Corps (V): smart Park
CSDN daily one practice 2021.11.06 question 1 (C language)
I found a wave of "alchemy artifact" in the goose factory. The developer should pack it quickly
scratch绘制正方形 电子学会图形化编程scratch等级考试二级真题和答案解析2022年6月
LVGL 8.2 Simple Colorwheel
LVGL 8.2 Checkboxes as radio buttons
& and - > priority
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
马斯克推特粉丝过亿了,但他在线失联已一周
Getting started with X86 - take over bare metal control
Pytorch Notebook. Nn. Batchnorm1d
Memory escape analysis
GeoffreyHinton:我的五十年深度学习生涯与研究心法
Use keil5 software to simulate and debug gd32f305 from 0
经典面试题:负责的模块,针对这些功能点你是怎么设计测试用例的?【杭州多测师】【杭州多测师_王sir】...
Every time I look at my colleagues' interface documents, I get confused and have a lot of problems...
潘多拉 IOT 开发板学习(HAL 库)—— 实验1 跑马灯(RGB)实验(学习笔记)
From introduction to mastery of MySQL 50 lectures (32) -scylladb production environment cluster building
Pandora IOT development board learning (HAL Library) - Experiment 1 running lantern (RGB) experiment (learning notes)