- 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.
- PaaS程序設計
- Mastering Natural Language Processing with Python
- Python應用輕松入門
- Raspberry Pi 2 Server Essentials
- Learning Firefox OS Application Development
- TypeScript實戰指南
- Visual C++數字圖像處理技術詳解
- ADI DSP應用技術集錦
- AutoCAD VBA參數化繪圖程序開發與實戰編碼
- Learn React with TypeScript 3
- Serverless架構
- Go語言精進之路:從新手到高手的編程思想、方法和技巧(1)
- Windows Embedded CE 6.0程序設計實戰
- Android移動開發案例教程:基于Android Studio開發環境
- 大數據時代的企業升級之道(全3冊)