- 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.
- Learning Scala Programming
- 小創(chuàng)客玩轉(zhuǎn)圖形化編程
- Python機(jī)器學(xué)習(xí):手把手教你掌握150個(gè)精彩案例(微課視頻版)
- QTP自動(dòng)化測(cè)試進(jìn)階
- 執(zhí)劍而舞:用代碼創(chuàng)作藝術(shù)
- Test-Driven Development with Django
- 代替VBA!用Python輕松實(shí)現(xiàn)Excel編程
- Python Interviews
- 創(chuàng)意UI:Photoshop玩轉(zhuǎn)APP設(shè)計(jì)
- 從零開(kāi)始學(xué)UI:概念解析、實(shí)戰(zhàn)提高、突破規(guī)則
- Android智能手機(jī)APP界面設(shè)計(jì)實(shí)戰(zhàn)教程
- IBM RUP參考與認(rèn)證指南
- Implementing Domain:Specific Languages with Xtext and Xtend
- H5頁(yè)面設(shè)計(jì)與制作(全彩慕課版·第2版)
- Python實(shí)戰(zhàn)指南:手把手教你掌握300個(gè)精彩案例