l0r3nz4cc10
l0r3nz4cc10

Reputation: 1283

Removing a value from a map

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.

Upvotes: 2

Views: 354

Answers (8)

Herring
Herring

Reputation: 173

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

Upvotes: 2

Cris
Cris

Reputation: 5007

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

Upvotes: 0

oliholz
oliholz

Reputation: 7507

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

Upvotes: 1

Jos&#233;Mi
Jos&#233;Mi

Reputation: 11952

Map<Something, List<String>> myMap = ....;
myMap.get(somethingInstance).remove("someString");

Upvotes: 1

ICR
ICR

Reputation: 14162

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

Upvotes: 1

Peter
Peter

Reputation: 6362

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

Upvotes: 3

Sylar
Sylar

Reputation: 2333

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

Upvotes: 1

jberg
jberg

Reputation: 4818

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")

Upvotes: 1

Related Questions