以有效的方式从Map中删除多个键?

时间:2013-07-16 11:51:23

标签: java map

我有一个Map<String,String>,其中包含大量键值对。现在我想从Map中删除选定的键。以下代码显示了我为实现这一目标所做的工作。

Set keySet = new HashSet(); //I added keys to keySet which I want to remove. 

然后:

Iterator entriesIterator = keySet.iterator();
while (entriesIterator.hasNext()) {
   map.remove( entriesIterator.next().toString());
} 

这很有效。我只是想知道,实现我的要求会有什么更好的方法?

4 个答案:

答案 0 :(得分:205)

假设您的论坛中包含您要删除的字符串,您可以使用the keySet methodmap.keySet().removeAll(keySet);

  

keySet返回此地图中包含的键的Set视图。该集由地图支持,因此对地图的更改将反映在集中,反之亦然。

受挫的例子:

Map<String, String> map = new HashMap<>();
map.put("a", "");
map.put("b", "");
map.put("c", "");

Set<String> set = new HashSet<> ();
set.add("a");
set.add("b");

map.keySet().removeAll(set);

System.out.println(map); //only contains "c"

答案 1 :(得分:3)

为了完整起见:

猜测if (size() <= collection.size()) { Iterator<?> it = iterator(); while (it.hasNext()) { if (collection.contains(it.next())) { it.remove(); } } } else { Iterator<?> it = collection.iterator(); while (it.hasNext()) { remove(it.next()); } } 实际上迭代了所有条目,但有一个小技巧:它使用较小集合的迭代器:

Function findValue() As String
Dim rng As Range
Dim row As Range
Dim cell As Range
Dim val As String

' Sets range of 5 columns to search in by column
Set rng = Range("A:E")                              

' searches through count of rows
For i = 2 To Range("A" & Rows.Count).End(xlUp).row  
For Each cell In rng.Cells(i)
    If IsEmpty(cell) = True Then
    MsgBox cell
    MsgBox i
    Else
        'MsgBox Range.(cell & i).Value
        findValue = cell
        Set rng = Range("A:E")
        Exit For
    End If
Next cell
Next i
End Function

答案 2 :(得分:1)

使用Java流:

keySet.forEach(map::remove);

答案 3 :(得分:1)

为了完整起见,由于Google在寻求实现此目标的方法时会将您带到这里:

map.entrySet().removeIf(entry -> /* decide what you want to remove here */ );

这不是假定您要删除一组预定义的键,而是假定您有一个应删除这些键的条件。从问题出发,目前尚不清楚这些密钥是手动添加还是基于某种条件添加。在后一种情况下,这可能是更干净的代码。

对于前一种情况,此(未经测试的)代码也可以工作:

map.entrySet().removeIf(entry -> keySet.contains(entry.getKey()) );

但是显然the answer provided by @assylias在这种情况下要干净得多!