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

会有一股神秘感。 提交于 2019-11-28 02:31:51

问题


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

BigDecimal samePrice;
Set<String> set;

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

However Java complains as follows:

The method toMap(Function, Function) in the type Collectors is not applicable for the arguments (Function, BigDecimal)

Why can't I use the BigDecimal from outside? If I write:

set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal()));

it would work, but that's of course not what I want.


回答1:


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.




回答2:


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)));



回答3:


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.



来源:https://stackoverflow.com/questions/36356041/how-to-create-a-map-with-java-stream-api-using-a-value-outside-the-stream

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