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("@"))
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<>()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With