Java List to Map convertion

后端 未结 2 1592
情话喂你
情话喂你 2021-01-12 14:39

I\'d like to convert a Map from List in java 8 something like this:

Map

        
2条回答
  •  生来不讨喜
    2021-01-12 15:03

    the toMap collector receives two mappers - one for the key and one for the value. The key mapper could just return the value from the list (i.e., either name -> name like you currently have, or just use the builtin Function.Identity). The value mapper should just return the hard-coded value of 0 for any key:

    namesMap = 
        names.stream().collect(Collectors.toMap(Function.identity(), name -> 0));
    

提交回复
热议问题