是否存在一个javaMap实现,其中键是已知的,但是值应该只在第一次访问时计算,因为计算值是昂贵的。
下面演示了我希望它如何工作。
someMap.keySet(); // Returns all keys but no values are computed.
someMap.get(key); // Returns the value for key computing it if needed.
原因是我有一个保存了一堆数据的东西,这个对象将数据作为 Map<String, String>
这是计算繁重的,因为计算值是昂贵的,但是键的计算成本很低。
Map必须保持其类型,所以我不能返回 Map<String, Supplier<String>>
. 他回来了 Map
可能返回为只读。
可以通过传入两个 Set<String>
定义键和 Function<String, String>
给定一个键返回它的值。
2条答案
按热度按时间cunj1qz11#
一个解决办法是有一张Map
Set
钥匙和钥匙Function
给定一个键就可以计算值。例如:
将此更改为通用应该很容易。
我怀疑有一个更好的解决方案存在,但是这对其他人来说可能已经足够好了。
vsdwdz232#
你可以这样做。Map有一个键和一个fnc类,其中包含一个函数和函数的参数。
第一次通过时,调用函数并计算、存储和返回值。后续调用返回存储值。
请注意,该值将替换计算函数。