<分区>
我想将下面的格式文件转换为映射“键、值”对变量。 我该怎么做?
第 10 类 母鸡 10 猫 10 枪 10 母鸡 10 狮子 10 猫头鹰 10 pig 10
<分区>
我想将下面的格式文件转换为映射“键、值”对变量。 我该怎么做?
第 10 类 母鸡 10 猫 10 枪 10 母鸡 10 狮子 10 猫头鹰 10 pig 10
最佳答案
因为你想为重复的键添加值,你可以使用 Map.merge()
。
来自docs :
If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value. Otherwise, replaces the associated value with the results of the given remapping function, or removes if the result is null. This method may be of use when combining multiple mapped values for a key.
例如:
public static void main(String... args) {
String seq = "cat 10 hen 10 cat 10 gun 10 hen 10 lion 10 owl 10 pig 10";
// [cat, 10, hen, 10, cat, 10, gun, 10, hen, 10, lion, 10, owl, 10, pig, 10]
String[] splitEntries = seq.split(" ");
Map<String, Integer> myMap = new HashMap<>();
for (int i = 0; i < splitEntries.length - 1; i += 2) {
// Iterate on splitEntries incrementing i by 2, so we can store the pairs:
// (0, 1), (2, 3), (4, 5), etc.
String key = splitEntries[i];
Integer value = Integer.valueOf(splitEntries[i + 1]);
// Pass Integer::sum so the previous value will be summed with the new one
// when trying to insert a repeated key
myMap.merge(key, value, Integer::sum);
}
System.out.println(myMap);
}
输出:
{hen=20, gun=10, owl=10, cat=20, lion=10, pig=10}
如果您不能使用 Java 8,则可以不调用 myMap.merge()
,而是检查是否已经为给定的 key
存储了一个值。如果没有,只需使 previousValue = 0
并将其求和到新的 value
。
Integer previousValue = myMap.get(key);
if (previousValue == null) {
previousValue = 0;
}
myMap.put(key, previousValue + value);
请注意,这不是线程安全的。例如,另一个线程可能会在您调用 get()
之后但在您调用 put()
之前更新 map ,从而导致存储错误的值。如果这是一个问题,您可以将此代码放在 synchronized
block 中。
关于java - 如何将 java 字符串转换为映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29837318/