将值放入java8映射时是否有类似getOrDefault的东西?

时间:2019-02-21 13:52:18

标签: java java-8 hashmap

在java8中,当从映射中获取一些值时,我们可以编写:

int keyCount=countMap.getOrDefault(key,0);

等于:

if(countMap.contains(key)){
    keyCount=countMap.get(key);
}else{
    keyCount=0;
}

问题是,有什么优雅的方法可以替换以下代码:

if(countMap.keySet().contains(key)){
    countMap.put(key,countMap.get(key)+1);
}else{
    countMap.put(key,1);
}

3 个答案:

答案 0 :(得分:2)

正如holger所述,您可以简单地将Map.merge用作:

countMap.merge(key, 1, Integer::sum)

请注意,文档也说明了其实现:

默认实现等效于对此映射执行以下步骤,然后返回当前值;如果不存在,则返回null:

V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
             remappingFunction.apply(oldValue, value);
if (newValue == null)
    map.remove(key);
else
    map.put(key, newValue);

答案 1 :(得分:0)

您正在寻找Java 8中也添加的compute方法,该方法将使用您正在使用的键以及一个import networkx as nx import matplotlib.pyplot as plt # nodes input nodes_id = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] nodes_x_y = [(1, 1.0), (2, 1.0), (3, 1.0), (4, 1.0), (5, 1.0), (2, 1.5), (3, 1.5), (4, 1.5), (5, 1.5), (2, 2.0), (3, 2.0), (4, 2.0), (5, 2.0), (2, 2.5), (3, 2.5), (4, 2.5), (5, 2.5), (1, 3.0), (2, 3.0), (3, 3.0), (4, 3.0), (5, 3.0)] # edges input those should match together↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ those should match together # edge labels edges_id = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23] # edge temperatures edges_tp_forw = [35.0, 33.0, 33.0, 33.0, 24.0, 33.0, 33.0, 33.0, 24.0, 14.0, 38.0, 33.0, 24.0, 14.0, 38.0, 33.0, 40.0, 14.0, 38.0, 33.0, 40.0, 40.0, 38.0, 33.0] # those should match together↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ those should match together edges_u = [1, 2, 3, 4, 1, 6, 7, 8, 5, 10, 7, 12, 9, 14, 11, 16, 13, 19, 15, 21, 18, 19, 20, 20] edges_v = [0, 1, 2, 3, 5, 2, 3, 4, 9, 6, 11, 8, 13, 10, 15, 12, 18, 14, 20, 16, 17, 18, 19, 21] # graph G = nx.OrderedDiGraph() # or: G = nx.DiGraph() # Add network nodes for k in nodes_id: G.add_node(nodes_id[k], pos=nodes_x_y[k]) # Add network edges for k in edges_id: G.add_edge(edges_u[k], edges_v[k], edge_color=edges_tp_forw[k], name=edges_id[k], labels=edges_id[k]) # position pos = nx.get_node_attributes(G, 'pos') # open plot f = plt.figure() plt.axis('off') # draw nodes nx.draw_networkx_nodes(G, pos=pos, node_size=00, node_shape='o', node_color='grey', font_weight='bold') # draw node labels bbox = dict(facecolor='grey', edgecolor='grey', boxstyle='circle') nx.draw_networkx_labels(G, dict(enumerate(nodes_x_y)), bbox=bbox, font_size=6) # draw edges max_value = max(edges_tp_forw) # Heatmap color map edge_cmap = plt.cm.get_cmap('coolwarm') # draw edges nx.draw_networkx_edges(G, pos, width=1, edge_color=edges_tp_forw, edge_cmap=edge_cmap, arrows=True) # draw edge labels edges_id = tuple(edges_id) edges = tuple(zip(edges_u, edges_v)) edges_labels_id_tp = [pair for pair in zip(edges_id, edges_tp_forw)] edges_draw_labels = dict(zip(edges, [elem for elem in edges_labels_id_tp])) bbox = dict(facecolor='white', edgecolor='grey', boxstyle='round') nx.draw_networkx_edge_labels(G, pos, edge_labels=edges_draw_labels, bbox=bbox, font_size=6, rotate=False) plt.show() plt.close() 来计算新值应基于在键和现有值上。因此,在您的情况下,它需要以下内容:

BiFunction

如果您提供的键在地图中不存在,则countMap.compute(key, (k, oldValue) -> oldValue == null ? 1 : oldValue + 1); 中的oldValue将为BiFunction;如果您在null中返回null,则地图中将没有任何内容。

这需要一点时间来适应,但是一旦掌握了它,这将是一个非常强大的方法。使用方法引用而不是内联lambda可能更易读(尽管更为冗长):

BiFunction

答案 2 :(得分:0)

对于不熟悉merge方法的用户:

countMap.put(key, countMap.getOrDefault(key,0)+1);