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

孤者浪人 提交于 2019-11-29 09:10:53

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.

Collectors#toMap expects two Functions

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

You can find nearly the same example within the JavaDoc

 Map<Student, Double> studentToGPA
     students.stream().collect(toMap(Functions.identity(),
                                     student -> computeGPA(student)));

As already said in the other answers, you need to specify a function which maps each element to the fixed value like element -> samePrice.

As an addition, if you want to specifically fill a ConcurrentHashMap, there is a neat feature that doesn’t need a stream operation at all:

ConcurrentHashMap<String,BigDecimal> map = new ConcurrentHashMap<>();
map.keySet(samePrice).addAll(set);

Unfortunately, there is no such operation for arbitrary Maps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!