java - 如何将 java 字符串转换为映射?

标签 java hashmap

<分区>

我想将下面的格式文件转换为映射“键、值”对变量。 我该怎么做?

第 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/

相关文章:

java - 如何使用BulkRequest将ArrayList发送到ElasticSearch中?

JavaFX:无法加载二进制样式表

java - 从edittext获取整数值

java - 为什么我的 GAE 数据存储查询返回的游标为 null?

java - 在 Spring Security 中添加新用户

java - 在迭代列表时从列表中删除对象

java - 使用序列号和分区 ID 从 Kinesis 获取记录

java - 如果列表中有字符串(在编译时给出): Is HashSet the fastest solution?

c++ - 在 unordered_map 中使用元组

java - 将 CSV 值转换为 JAVA 中的 HashMap 键值对