簡體   English   中英

Java-如何檢查ArrayList中是否有一個值是HashMap中的鍵值?

[英]Java - How to check if there is a value inside an ArrayList that is a value of a key in a HashMap?

if (!mainMethods.matrix.isEmpty()) {
    for (int i = 0; i < mainMethods.matrix.values().size(); i++) {
        if (mainMethods.matrix.containsValue(getArrayList()[i].getValue().toString().contains(textValue.getText()))) {
            String errorTitle = "Impossível completar a operação.";
            String errorMessage = "Não é possível adicionar um valor de chave repetido.";
            JOptionPane.showMessageDialog(getParent(), errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE);            
        }
    }

有一個稱為“矩陣”的HashMap,它具有很多鍵。 每個鍵的值是一個具有自己值的ArrayList。 考慮到這一點,我無法找到一種方法來測試ArrayList-Values內部是否存在特定值,因為如果將String參數傳遞給HashMap的方法“ .containsValue()”,則該方法將找到一個ArrayList對象,測試將為假。 因此,就像在示例中一樣,我必須做一些相當瘋狂的事情。 如您所見,沒有諸如“ getArrayList()”或“ getValue()”之類的東西。 這是一個非常復雜的情況,我試圖用“偽代碼”解釋我的觀點。

你知道如何解決嗎?

如果我正確理解您的意見,則應該可以執行以下操作:

private <K, V> V getValueIfKeyContains(final Map<List<K>, V> map, final K desiredKey) {
    for (final Entry<List<K>, V> entry : map.entrySet()) {
        if (entry.getKey().contains(desiredKey)) {
            return entry.getValue();
        }
    }
    return null;
}

因此,您可以遍歷Map並檢查每個鍵是否包含所需的desiredKey

強烈建議兩件事:

  1. 不要在Map使用可變值作為鍵。 這將導致大量問題,因為將它們添加到Map 可以更改。
  2. 如果要檢查是否contains ,請不要使用List 這是O(n)操作,即,它花費的時間與List的大小成比例。 它必須遍歷List每個元素,直到找到正確的元素為止。 使用Set ,操作將變為O(1) ,即恆定時間。

做一件事。 將數據結構更改為...

舊的是:

HashMap <Key, ArrayList>

改成

HashMap<Key, HashMap<Value in ArrayList at index[i], Value in ArrayList at index[i]>>

這是假設您在arrayList中有不可變的對象。 因此,一旦您使用鍵獲取對象。 您可以再次使用其鍵在內部地圖中搜索。

您可以使用迭代器並單獨檢查每個數組列表:

Iterator it = mainMethod.matrix.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    If(pairs.getValue().contains(your value)
    {
        // do stuff
    }
}

使用for-each循環遍歷ArrayList (我假設它們持有String ),並使用其contains()方法測試其中是否存在值。

if (!mainMethods.matrix.isEmpty()) {
  for (List<String> list : mainMethods.matrix.values()) {
    if (list.contains(textValue.getText())) {
      String errorTitle="Impossível completar a operação.";
      String errorMessage="Não é possível adicionar um valor de chave repetido.";
      JOptionPane.showMessageDialog(
        getParent(), errorMessage, errorTitle, JOptionPane.ERROR_MESSAGE);
    }
  }
}

如果可能,請切換為使用Set而不是List因為搜索集合要快很多倍。 但是集合將不允許您重復。 因此,請選擇更適合您要求的產品。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM