Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check in Map of list if exists value for specific key Java 8

In Java 7 I have

Map<String, List<String>> m = new HashMap<String, List<String>>();
boolean result = false;
m.put("Name1", Arrays.asList("abc*1"));
m.put("Name2", Arrays.asList("abc@*1"));


for (Map.Entry<String, List<String>> me : m.entrySet()) {
    String key = me.getKey();
    List<String> valueList = me.getValue();
    if (key.equals("Name2"){
        System.out.print("Values: ");
        for (String s : valueList) {
            if(s.contains("@"){
                result = true;
            }
        }
    }
} 

How can I get în a bool result for Name2 if it contains @ using any match?

I tried using The following Code but I Don t know how to use IT for specific key

result = m.values().stream().anyMatch(v -> v.contains("@"))
like image 903
Marinescu Raluca Avatar asked Nov 28 '22 22:11

Marinescu Raluca


1 Answers

Do the following:

boolean result = m.getOrDefault("Name2", Collections.emptyList()).stream()
    .anyMatch(i -> i.contains("@"));

If the Map contains a correct key, check whether any of its element of the List as value contains the particular character. If the Map doesn’t contain the key, mock the empty Collection which doesn't contain anything at all and the result is evaluated automatically as false.

Edit: As @Michael suggested, using the Collections.emptyList() is a better choice than new ArrayList<>().

like image 104
Nikolas Charalambidis Avatar answered May 01 '23 16:05

Nikolas Charalambidis