// "Collapse loop with stream 'collect()'" "true-preview" import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Main { List test(Map> map, int limit) { List list = map.entrySet().stream().filter(entry -> entry.getValue() != null).flatMap(entry -> entry.getValue().stream()).filter(str -> str.contains("foo")).limit(limit).collect(Collectors.toList()); return list; } }