Skip to content
Advertisement

Iterate Java Map but after skipping 1-st element

I have this Java Map:

Map<String, String> map = new HashMap<>();
map.put("//div[@col-id='actualSourceLPName']", "LP4");
map.put("//div[@col-id='actualSourceLPName']", "LP4s");

I want to skip the first one:

for (String key : map.entrySet().stream().skip(1)) {
    compareValues(driver, key, map.get(key));
}

But I get error: foreach not applicable to type 'java.util.stream.Stream<java.util.Map.Entry<java.lang.String,java.lang.String>>'

Do you know how I can fix this issue?

Advertisement

Answer

First use a LinkedHashMap if you want it ordered:

Map<String, String> map = new LinkedHashMap<>();
map.put("//div[@col-id='actualSourceLPName']", "LP4");
map.put("//div[@col-id='actualSourceLPName']", "LP4s");

You are trying to iterate a stream which doesn’t work that way. Try this:

map.entrySet().stream().skip(1).forEach(e -> {
    compareValues(driver, e.getKey(), e.getValue());
});

Alternatively you can convert your stream to a list. Now your driver variable doesn’t have to be “effectively final”.

for (String key : map.entrySet().stream().skip(1).map(e -> e.getKey()).collect(Collectors.toList())) {
    compareValues(driver, key, map.get(key));
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement