java使用ComputeFabSent和ComputeiPresent将列表放入映射
我有一堆代码对我来说很好:
for (String word : distinctWordsInOneLigne) {
Map<String, List<Integer>> map = new HashMap<>();
if (!word.isEmpty()) {
List<Integer> linePositionsOfWord = new LinkedList<>();
if (currentLine.contains(word)) {
linePositionsOfWord.add(numLine);
if (mapAllWordsPositionInFilesInFolder.containsKey(word)) {
Map<String, List<Integer>> mapList = mapAllWordsPositionInFilesInFolder.get(word);
if (mapList.containsKey(filePath)) {
List<Integer> list = mapList.get(filePath);
list.add(numLine);
} else {
mapList.put(filePath, linePositionsOfWord);
}
} else {
map.put(filePath, linePositionsOfWord);
mapAllWordsPositionInFilesInFolder.put(word, map);
}
}
}
}
注意:Map<String, Map<String, List<Integer>>> mapAllWordsPositionInFilesInFolder = new HashMap<>();
我这样做的结果是:
{word1={file2.txt=[7], file1.txt=[1, 2]}, word2={file2.txt=[1, 2, 9, 13], file5.txt=[2, 3, 9]}}
现在我想得到一些结果,但是现在通过使用ComputeIfAbsent
&ComputeIfPresent
而不是{
我试过了,但没有成功:
mapAllWordsPositionInFilesInFolder.computeIfAbsent(word,v -> new HashMap<>())
.computeIfAbsent(filePath, val -> linePositionsOfWord);
mapAllWordsPositionInFilesInFolder.computeIfPresent(word,(k,v)->{
v.computeIfPresent(filePath, (x, y) -> linePositionsOfWord.add(numLine));
return v;
});
我需要帮助!谢谢:)
# 1 楼答案
你不会用
computeIfPresent()
来做这件事,但你会像这样使用computeIfAbsent()
:最初的代码写得很糟糕。即使不使用
computeIfPresent()
,也可以对其进行大量清理,消除重复代码。这是应该如何写的:通过内联,这可以简化为: