如何将函数作为参数传递给computeIfAbsent方法?

5

我是一个C#转Java的新手。

java.util.function有一个名为Function的接口,它是MapcomputeIfAbsent方法的输入。

我想定义并将该函数委托给computeIfAbsent方法。

map.computeIfAbsent(key, k => new SomeObject())

这个代码“works”(可行),但我希望使用回调函数来实现它。问题在于,Function要求输入参数必须被定义。如何将其设置为void或没有参数?

map.computeIfAbsent(key, func);

2
为什么“函数需要定义输入参数”是一个问题?你能描述一下你实际想做什么吗? - Holger
我的computeIfAbsent在一个循环内。假设循环执行了25000次。 如果我遵循传统的方法,每次lambda函数都会被创建并传递给computeIfAbsent函数。为什么它总是要被创建?我们不能将其存储在函数中并进行传递吗? - Mayur Patil
4
可以。如果这是你的问题,为什么不直接问这个问题,而不是与之完全无关的“如何将其设置为空或不带参数”? - Holger
5个回答

7

computeIfAbsent 总是有一个参数作为传递的 Function 的输入 - 这个参数就是键。

因此,你可以这样编写:

map.computeIfAbsent(key, k -> new SomeObject());

假设你的Map的键是String类型,你也可以这样写:

Function<String,SomeObject> func = k -> new SomeObject();
map.computeIfAbsent(key, func);

1
我正在使用Map集合。 由于我的键类型是字符串,所以我使用了Function<String,SomeObject> func = k -> new SomeObject()修改了您的答案。 - Mayur Patil
函数<MapKeyDataType, FunctionReturnDataType> - Mayur Patil

3
您可以创建一个lambda函数接受该参数并调用您的函数,忽略该参数。
map.computeIfAbsent(key, k -> func());

2
如果func不具有计算成本且没有副作用,则可以直接使用putIfAbsent(注意是'put'而不是'compute')并直接调用该方法。它在语义上是等效的。
map.putIfAbsent(key, func());

func将被评估每一次,无论它是否要被插入,但只要它很快就不是一个问题。


只有当func()返回一个Function<K, V>时,它才能编译。 - daniu
抱歉,我在 compute 那里卡住了,错过了 put - daniu

0

computeIfAbsent(Key, Function) 用于使用给定的映射函数计算给定键的值,如果该键尚未与值关联(或映射到 null),则将计算出的值输入 Hashmap 中,否则返回 null。根据语法而定。

public V computeIfAbsent(K key, Function<? super K, ? extends V> remappingFunction)

你可以这样写 -

map.computeIfAbsent(key, k -> Object()); 或者

map.computeIfAbsent(key, k -> fun());

0

computeIfAbsent 接受两个参数:

  • key - 需要关联特定值的键
  • mappingFunction - 计算一个值的函数 (这是 Function 类型的函数接口,它接受一个参数并返回一个结果)。

除了使用 computeIfAbsent 方法之外,没有其他必要指定这些参数的方法。以下是使用此 Map 方法的示例:

输入:Map<String,Integer> map:{four = 4,one = 1,two = 2,three = 3,five = 5}

map.computeIfAbsent("ten", k -> new Integer(10));   // adds the new record to the map
map.computeIfAbsent("twelve", k -> null);           // record is not added, the function returns a null
map.computeIfAbsent("one", k -> new Integer(999999));   // record is not updated, the key "one" already exists -
                                                        // and has a non-null value
map.put("eleven", null);                                // new record with null value
map.computeIfAbsent("eleven", k -> new Integer(11));    // updates the record with new value

输出结果:{four=4, one=1, eleven=11, ten=10, two=2, three=3, five=5}


考虑以下代码map.computeIfAbsent("ten", k -> new Integer(10));

这段代码表示我想要向map中插入一个新的映射(键值对)。方法computeIfAbsent需要指定,即"ten"。是由Function生成的,该函数以键作为输入参数并产生结果;结果被设置为映射的值。

在这个例子中,键值对被添加到了map中:"ten",10。

lambda表达式k -> new Integer(10)Function<String,Integer>的实例。这段代码也可以表示为:

Function<String, Integer> fn = k -> new Integer(10);
map.computeIfAbsent("ten", fn);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接