2

I have a Map<Something, List<String>> map. I want to remove a String from the List<String>.

Is that possible ? How do I do that ?

I don't want to remove the mapping, just alter the 'value' of an entry.

I have tried map.values().remove("someString"), but that doesn't seem to work.

8 Answers 8

3

Try map.get(somethingKey).remove("someString").

2

if you want to remove a String from a particular map item, you should use something like this:

if (map.containsKey(somethingParticular) && map.get(somethingParticular)!=null)
    map.get(somethingParticular).remove("someString")

if you want to remove "someString" from all map items, its better to do thw following:

for(List<String> list : map.values()) {
    if (list!=null)
        list.remove("someString");
}
1
  • Good idea for the containsKey() and null checks.
    – Peter
    Jun 14, 2011 at 9:28
1

You need to actually have a value to index into the map also.

Then you can do something like this:

map.get(mapValue).remove("someString")

1

Try this: map.get(key).remove("someString")

1

Do you want to remove the string from all the string lists, or a specific one?

If you want a specific one, then you need to get the List<String> by key:

map.get(thekey).remove("someString")

If you want to remove them all, then you need to loop over the values, as they're a collection of List<String>'s.

for (List<String> list : map.values()) {
    list.remove("someString");
}
1
Map<Something, List<String>> myMap = ....;
myMap.get(somethingInstance).remove("someString");
1

map.values() returns a Collection of List<String>. You have to iterate over the values and search for your key in every list.

    Map<String, List<String>> map = new HashMap<String, List<String>>();
    Collection<List<String>> values = map.values();
    for( List<String> list : values ) {
        list.remove( "someString" );
    }
0

Yes it is possible :

Map<String,List<Integer>> map = new HashMap<String, List<Integer>>();
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
map.put("intlist",intList);
System.out.println(map.get("intlist"));
intList = map.get("intlist");
intList.remove(1);
intList.add(4);     
//they will be the same (same ref)
System.out.println(intList);
System.out.println(map.get("intlist"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.