英文:
Improving elegance Java maps for putting/retrieving items
问题
我有一个简单的代码片段:
String partition = getPath(data);
if (partitioningMap.containsKey(partition)) {
partitioningMap.get(partition).add(data);
} else {
partitioningMap.put(partition, new ArrayList<>(Arrays.asList(record)));
}
我意识到这已经很简单了,但出于好奇,我想知道是否有一种更简洁的方法来执行这些操作,而不需要 if-else 块。
我正在研究类似于 putIfAbsent
的东西,但我通过在该键上使用 add
来修改列表。我考虑过使用 computeIfAbsent
,但 computeIfAbsent
和 computeIfPresent
仍然是两个不同的调用。
英文:
I have a simple snippet:
String partition = getPath(data);
if (partitioningMap.containsKey(partition)) {
partitioningMap.get(partition).add(data);
} else {
partitioningMap.put(partition, new ArrayList<>(Arrays.asList(record)));
}
I realize this is already pretty simple, but out of curiosity, I'm wondering if there is a more succinct way of doing these operations without an if-else block.
I'm looking into something like putIfAbsent
, but I'm modifying the list via add
on that key. I was thinking about computeIfAbsent
, but computeIfAbsent
and computeIfPresent
are still 2 different calls.
答案1
得分: 2
在Java 8之前:
String partition = getPath(data);
if (!partitioningMap.containsKey(partition)) {
partitioningMap.put(partition, new ArrayList<>());
}
partitioningMap.get(partition).add(data);
在Java 8中可以这样做:
partitioningMap.computeIfAbsent(getPath(data), d -> new ArrayList<>()).add(data);
英文:
There is a couple ways you can do it:
Prior to java 8:
String partition = getPath(data);
if (!partitioningMap.containsKey(partition)) {
partitioningMap.put(partition, new ArrayList<>());
}
partitioningMap.get(partition).add(data);
In java 8 you can do:
partitioningMap.computeIfAbsent(getPath(data), d -> new ArrayList<>()).add(data);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论