简体   繁体   中英

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);            
        }
    }

There is this HashMap called "matrix", and it has lots of keys. The value of every key is an ArrayList that has its own values. Considering this, I can't find a way to test whether there is a specic value inside the ArrayList-Values, because if I pass an String argument to the method ".containsValue()" of the HashMap, the method will find an ArrayList object and the test will be false. Therefore I must do something rather insane, just like I did in the example. As you can see, there's no such thing like "getArrayList()", or "getValue()". It's a very complicated situation and I tried to explain my point with "Pseudo-Code".

Do you know how to solve it?

If I understand you correctly, something like this ought to work:

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;
}

So you loop over the Map and check whether each key contains the desiredKey .

I would strongly recommend two things:

  1. Don't use mutable values as keys in a Map . This causes massive issues as they can change after they are added to the Map .
  2. Don't use List if you want to check contains . This is an O(n) operation, ie it takes time proportional to the size of the List . It has to loop over every element in the List until it finds the right one. Use a Set and the operation becomes O(1) , ie constant time.

Do one thing. Change your data structure as...

Old one is:

HashMap <Key, ArrayList>

Change to

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

This is assuming you have immutable objects inside the arrayList. So now once you get an object using key. You can again search in inner map using its keys.

You could use an iterator and check each arraylist individually:

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

Use a for-each loop to iterate over your ArrayList s (I've assumed they hold String s) and use their contains() method to test if a value is present within or not.

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);
    }
  }
}

If possible switch to using a Set instead of a List as searching a set is many times faster. But sets won't allow you to have duplicates. So, choose what suits your requirements better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM