【问题标题】:Edit value of a map entry without replace whole map entry编辑地图条目的值而不替换整个地图条目
【发布时间】:2020-08-18 03:03:27
【问题描述】:

我目前正在搜索一些类似于 Map 的 DataStrucutre,但不同之处在于,mapentry 的值是可编辑的。

我的地图如下所示:Map<String, List<String>>。但有时在代码中我想将一个项目添加到地图条目的列表中。但这不起作用,因为我认为如果不将整个条目替换为replaceput,我将无法编辑映射条目的值。

是否有一些类似的 DataStructure 看起来类似于 Map 但我可以编辑条目的值?

代码:

for(String p : paths){
            String[] arr = p.split("\\\\", 2);
            //achtung was tun wen p nur ein element nur mehr ist und keine File.seperator besitzt???
            List<String> list = geteilt.get(arr[0]);

            if(list != null){
                if(arr.length > 1){
                    //Here is my problem. I want to add a String to the list
                    list.add(arr[1]);

                }
            } else {
                if(arr.length > 1){
                    geteilt.put(arr[0], List.of(arr[1]));
                } else {
                    geteilt.put(arr[0], List.of());
                }
            }

        }

【问题讨论】:

  • 请添加您的代码,并说明什么不适合您。

标签: java dictionary data-structures collections


【解决方案1】:

我认为如果不替换 整个条目使用replaceput

这是不正确的。下面给出一个例子来证明这一点:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, List<String>> map = Map.of("abc", new ArrayList<>(Arrays.asList("a", "b")), "xyz",
                new ArrayList<>(Arrays.asList("x", "y", "z")));
        System.out.println("Original: " + map);

        map.get("abc").set(1, "c");
        map.get("abc").add("p");
        System.out.println("Updated: " + map);
    }
}

输出:

Original: {xyz=[x, y, z], abc=[a, b]}
Updated: {xyz=[x, y, z], abc=[a, c, p]}

【讨论】:

  • 我的代码不起作用,因为我使用的是List.of()。您正在使用new ArrayList&lt;&gt;(Arrays.asList( something here),这很有效。谢谢
【解决方案2】:

如果您使用的是 java 8 或更高版本,则可以使用computecomputeIfPresent。 例如:

        Map<String, List<String>> test = new HashMap<>();
        test.put("1", Arrays.asList("a", "b", "c"));
        test.put("2", Arrays.asList("a", "b", "c"));

        System.out.println(test); // prints {1=[a, b, c], 2=[a, b, c]}
        test.computeIfPresent("1", (k, v) -> {
            v.set(2, "changed");
            return v;
        });
        System.out.println(test); // prints {1=[a, b, changed], 2=[a, b, c]}

如果您使用的是任何旧版本的 java,我的建议是使用 util 方法。

【讨论】:

    【解决方案3】:

    您不需要任何专门针对您的案例的新数据结构,即 Map >

    编辑地图条目:

    1. 获取要修改的键的值。

    2. 返回的值为List,你可以使用常用的list方法修改这个值,变化会反映为Map值只是引用到了List。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 2011-04-24
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 2020-01-11
      相关资源
      最近更新 更多