Home > OS >  Modify values in a Map, removing digits from each String
Modify values in a Map, removing digits from each String

Time:08-14

I've got Hashmap:

Map<Integer, String> map = new HashMap<>();

values in map:

{1=Thi1s, 2=is2, 3=3a, 4=T4est}

I need to remove digits from values like:

{1=This, 2=is, 3=a, 4=Test}

something like:

firstname1 = firstname1.replaceAll("\\d","");

but for HashMap.

How can I achieve it?

CodePudding user response:

Use Map.replaceAll(BiFunction<? super K,? super V,? extends V>) A full example is

Map<Integer, String> map = new HashMap<>();
map.put(1, "Thi1s");
map.put(2, "is2");
map.put(3, "3a");
map.put(4, "T4est");
System.out.println(map);
map.replaceAll((i, s) -> s.replaceAll("\\d ", ""));
System.out.println(map);

Which outputs (as requested)

{1=Thi1s, 2=is2, 3=3a, 4=T4est}
{1=This, 2=is, 3=a, 4=Test}

Alternatively, you could replace the digits when you add the values to the map in the first place.

CodePudding user response:

You can iterate and replace the value:

map.entrySet().forEach(e -> {
    e.setValue(e.getValue().replaceAll("\\d", ""));
});
  • Related