Improving elegance Java maps for putting/retrieving items

huangapple go评论78阅读模式
英文:

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,但 computeIfAbsentcomputeIfPresent 仍然是两个不同的调用。

英文:

I have a simple snippet:

            String partition = getPath(data);
            if (partitioningMap.containsKey(partition)) {
                partitioningMap.get(partition).add(data);
            } else {
                partitioningMap.put(partition, new ArrayList&lt;&gt;(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&lt;&gt;());
}
partitioningMap.get(partition).add(data);

In java 8 you can do:

partitioningMap.computeIfAbsent(getPath(data), d -&gt; new ArrayList&lt;&gt;()).add(data);

huangapple
  • 本文由 发表于 2020年8月11日 06:07:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63348659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定