官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 施甸县| 武宁县| 永登县| 湘乡市| 左权县| 中宁县| 郴州市| 灵丘县| 太原市| 六安市| 乐平市| 栾川县| 遂溪县| 遂平县| 嘉祥县| 老河口市| 石首市| 温泉县| 温泉县| 宁远县| 乌海市| 从江县| 安阳县| 滦平县| 延边| 泸水县| 南昌县| 观塘区| 焦作市| 长阳| 漳州市| 西贡区| 宝鸡市| 会理县| 吉林省| 贵港市| 化德县| 申扎县| 法库县| 丰宁| 利辛县|