【问题标题】:I need to check whether adding value already exists in Map and add values to list of integers in Map我需要检查 Map 中是否已经存在添加值并将值添加到 Map 中的整数列表
【发布时间】:2019-08-06 21:26:46
【问题描述】:

我需要创建一个以字符串为键、整数列表为值的 Map。我创建了地图,创建了从 txt 文件中获取的单词的标记化。现在我正在尝试将键和值放入映射中,但我仍然收到错误。我想知道也许我的地图创建错误,但我没有看到任何其他方式来创建此地图。

我一直在尝试用“put”函数添加这个地图,这样我什至无法编译这个程序

Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();
        //Map<String, Integer> map = new HashMap<String, Integer>();    
        int numberOfFiles;
        File directory = new File("C:/Users/User/Desktop/documents java project/");
        numberOfFiles = directory.list().length;


        for(int i = 1; i <= numberOfFiles; i++) {
            //tokenization of string
            String filePath = "C:/Users/User/Desktop/documents java project/document "+ i +".txt";
            String fileData = readFile(filePath);
            String delimiter = " ";
            String fileWords [] = fileData.split(delimiter);
            //words.add(fileWords);
            int numberOfWords = fileWords.length;

            for(int j = 0; j < numberOfWords; j++) {

                map.put(fileWords[j], i);

            }
        }
}

【问题讨论】:

  • 地图是Map&lt;String, List&lt;Integer&gt;&gt;,但您尝试将单个整数作为值与map.put(fileWords[j], i)。您打算在地图中存储什么?

标签: java list dictionary tokenize


【解决方案1】:

您的Map 期望值是List&lt;Integer&gt;,但您正试图将int 放入其中:

map.put(fileWords[j], i);

相反,您需要创建一个List&lt;Integer&gt; 并将其作为值,例如:

if (!map.containsKey(fileWords[j])) {
    map.put(fileWords[j], new ArrayList<>());
}
map.get(fileWords[j]).add(i);

这会将新的空List 添加到您的Map(如果它尚不存在),然后它将i 的值添加到列表中。如果它已经存在,它只会将i 添加到已经存在的列表中。

如果以上内容对您的口味来说太罗嗦,也可以使用Map.computeIfAbsent() 来完成:

map.computeIfAbsent(fileWords[j], k -> new ArrayList<>()).add(i);

如果您不想存储重复项,可以改用Set。将您的声明更改为:

Map<String, Set<Integer>> map = new HashMap<>();

然后,添加项目:

map.computeIfAbsent(fileWords[j], k -> new HashSet<>()).add(i);

【讨论】:

  • 太好了,感谢您的快速回答和帮助。
  • 也许还有一件事。现在一切都很好,但是例如对于某些键,我有一个像 {word = [1,1,2,2] 一样重复的值,因为这个词在第一个和第二个文档中存在两次。我怎样才能摆脱双倍的价值?
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多