问题描述:

I have the following HashMap (HashMap<String, String[]>) and was wondering, if there is a method to remove a specific String from the array of a specific key.

I've found only methods to remove one key basing on a value, but for example, I have:

("key1", new String[]{"A", "B", "C"})

How can I remove only B?

网友答案:

Here's s plain Java solution:

map.computeIfPresent("key1", (k, v) -> Arrays.stream(v)
  .filter(s -> !s.equals("B")).toArray(String[]::new));
网友答案:

You would get the values for the specific key and remove the given value from it, then put it back into the map.

public void <K> removeValueFromKey(final Map<K, K[]> map, final K key, final K value) {
    K[] values = map.get(key);
    ArrayList<K> valuesAsList = new ArrayList<K>(values.length);
    for (K currentValue : values) {
        if (!currentValue.equals(value)) {
            valuesAsList.add(currentValue);
        }
    }

    K[] newValues = new K[valuesAsList.size()];
    newValues = valuesAsList.toArray(newValues);
    map.put(key, newValues);
}

Be aware that the runtime of course is linear to the size of the given array. There is no faster way, because you need to iterate over each element of the array to find all values that are equal to the given value.

However, you could do a faster implementation with other data structures, if that is practicable. For example sets would be better than arrays, or any other data structure that implements contains is faster than O(n).

The same holds for space complexity; you have a peak where you need to hold both arrays in the memory. This is because the size of an array cannot be changed; the method will construct a new array. Thus you will have two arrays in the memory, O(2n).

A Collection<String> may be a better solution, depending on how often you'll call the method, compared to how many elements a map holds.

Another thing is that you can speed up the progress by guessing a good initial capacity for the ArrayList.

相关阅读:
Top