- Apache Spark 2.x for Java Developers
- Sourav Gulati Sumit Kumar
- 210字
- 2021-07-02 19:01:59
Map collectors
The streams can also be collected as a map; however, the key-value pairs need to be identified in order to create a map:
//Map Collectors
Map<String , Integer>mapCollected=orderedSetCollected.stream().collect(Collectors.toMap(x->x.toString(),x->x.toString().length() ));
System.out.println("The generated Map values are :: "+mapCollected);
In the preceding implementation, it is assumed that the keys are unique; however, that may not be always the case and we might get an IllegalStateException exception saying that a duplicate key exists. To handle such scenarios, an overloaded method of toMap() can be used as follows:
//Map Collectors with duplicate key handling
Map<Object, List<Integer>> mapWithDupVals=streamSupplier.get().collect(Collectors.toMap(x->x.toString(),
//KeyMapper
x -> {List <Integer>tmp = new ArrayList <> (); tmp.add(x.toString().length()); returntmp;},
//ValueMapper
(L1, L2) -> { L1.addAll(L2); returnL1;} //MergeFunction
));
System.out.println("The generated Map values with duplicate values::" + mapWithDupVals);
Here the toMap() method accepts three arguments: KeyMapper, ValueMapper, and MergeFunction. The role of KeyMapper is to produce the key value of the map, while the role of ValueMapper is to map the value in this case in a list. Merge function has a special role of conflict avoidance as per the logic of the function, here the logic being to add both the elements in a list. There can be multiple ways to handle duplicate keys; the preceding case is only one of the many ways of doing so.
- 微服務(wù)設(shè)計(jì)(第2版)
- CentOS 7 Server Deployment Cookbook
- 編程卓越之道(卷3):軟件工程化
- C#編程入門指南(上下冊)
- INSTANT Weka How-to
- 深入理解Java7:核心技術(shù)與最佳實(shí)踐
- 64位匯編語言的編程藝術(shù)
- Learning Apache Kafka(Second Edition)
- 重學(xué)Java設(shè)計(jì)模式
- Oracle JDeveloper 11gR2 Cookbook
- PHP+Ajax+jQuery網(wǎng)站開發(fā)項(xiàng)目式教程
- 軟件測試綜合技術(shù)
- Vue.js光速入門及企業(yè)項(xiàng)目開發(fā)實(shí)戰(zhàn)
- R語言數(shù)據(jù)挖掘:實(shí)用項(xiàng)目解析
- Python物理建模初學(xué)者指南(第2版)