如何使用流外部的值使用Java流API创建映射? [英] How to create a map with Java stream API using a value outside the stream?

查看:148
本文介绍了如何使用流外部的值使用Java流API创建映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想初始化 Map< String,BigDecimal> ,并希望始终将相同的 BigDecimal 值设置为在流之外。

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

然而,Java抱怨如下:

However Java complains as follows:


收集器类型中的toMap(Function,Function)方法不适用于参数
(函数,BigDecimal)

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

为什么我不能从外面使用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.

推荐答案

toMap(keyMapper,valueMapper) 是一个函数,它接受stream元素并返回map的值。

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.

这篇关于如何使用流外部的值使用Java流API创建映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆