0

I have a list of Strings:

List<String> countries;

it contains countries, e.g.:

Austria, Poland, England

and I have a map:

Map<String, String> data;

This map contains entries such as:

one   | Austria
two   | Germany
three | France

etc.

How can I filter the map so that at the end it has only the entries that are not in the list? For the example given above, the output map would contain:

two   | Germany
three | France

I tried using java8 filters, but with no positive result, could you help me with that?

randomuser1
  • 2,733
  • 6
  • 32
  • 68

1 Answers1

2

Maybe with Java8+ you can use :

data.values().removeIf(s -> countries.contains(s));

display the result you can use :

data.forEach((k, v)-> System.out.println(k + " | " + v));

Outputs

two | Germany
three | France
guest
  • 128
  • 3
  • thank you, that looks great, one last question - is there any way in java8 to also do the other way around, e.g. to leave in map only the records that are present in the list? – randomuser1 Feb 19 '19 at 13:23
  • 1
    Yes of course you can just put **!** the not anchor before the condition like `data.values().removeIf(s -> !countries.contains(s));` :) – guest Feb 19 '19 at 13:27
  • 1
    But this has no advantage over the old `data.values().removeAll(countries);` or `data.values().retainAll(countries);`. The new `removeIf` operation is a great tool for more complex conditions, but you should not overuse it. – Holger Feb 19 '19 at 15:15