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

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.

主站蜘蛛池模板: 鱼台县| 定安县| 来安县| 巴林右旗| 同仁县| 阜新| 沙洋县| 专栏| 莒南县| 临潭县| 永新县| 马尔康县| 洛川县| 高碑店市| 西安市| 枣阳市| 淮安市| 丽江市| 兴化市| 久治县| 清丰县| 同德县| 辽源市| 营山县| 广宗县| 建平县| 临沭县| 犍为县| 太白县| 卫辉市| 宜春市| 额济纳旗| 忻州市| 南皮县| 墨脱县| 临湘市| 麻城市| 准格尔旗| 南阳市| 阳城县| 冷水江市|