Java8 streams : Transpose map with values as list

前端 未结 4 2132
情歌与酒
情歌与酒 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:19

    It's a bit scary (I generally try to break it down to make it more readable) but you could do it this way:

    Map> transposeMap = new HashMap<>();
    
    map.forEach((key, list) -> list.stream().forEach(
        elm -> transposeMap.put(elm,
            transposeMap.get(elm) == null ? Arrays.asList(key) : (Stream.concat(transposeMap.get(elm).stream(),
                Arrays.asList(key).stream()).collect(Collectors.toList())))));
    

    Assuming Map> map is your original Map that you want to transpose. transposeMap will have transposed map that you need.

提交回复
热议问题