Java8 streams : Transpose map with values as list

前端 未结 4 2125
情歌与酒
情歌与酒 2020-12-03 08:45

I have map with key as String and value as List. List can have 10 unique values. I need to convert this map with key as Integer and value as List. Example as below :

4条回答
  •  爱一瞬间的悲伤
    2020-12-03 09:45

    Alexis’ answer contains the general solution for this kind of task, using flatMap and a temporary holder for the combination of key and flattened value. The only alternative avoiding the creation of the temporary holder objects, is to re-implement the logic of the groupingBy collector and inserting the loop over the value list logic into the accumulator function:

    Map> mapT = map.entrySet().stream().collect(
        HashMap::new,
        (m,e) -> e.getValue().forEach(
                     i -> m.computeIfAbsent(i,x -> new ArrayList<>()).add(e.getKey())),
        (m1,m2) -> m2.forEach((k,v) -> m1.merge(k, v, (l1,l2)->{l1.addAll(l2); return l1;})));
    

提交回复
热议问题