How to create a map with Java stream API using a value outside the stream?

后端 未结 3 471
灰色年华
灰色年华 2020-12-18 19:48

I want to init a Map and want to always put the same BigDecimal value from outside of the stream.

BigDeci         


        
3条回答
  •  没有蜡笔的小新
    2020-12-18 20:09

    The second argument (like the first one) of toMap(keyMapper, valueMapper) is a function that takes the stream element and returns the value of the map.

    In this case, you want to ignore it so you can have:

    set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice));
    

    Note that your second attempt wouldn't work for the same reason.

提交回复
热议问题