I have started working with Java 8 and trying to convert some loops and old syntax in my code to lambdas and streams.
So for example, I\'m trying to convert this whi
You can achieve it with a stream nested in a stream created from oldList list. Nested stream plays role of mapping current value from oldList with a mapper defined in map, e.g.
public static void main(String[] args) {
final List oldList = Arrays.asList("asd-qwe", "zxc", "123");
final Map map = new HashMap() {{
put("asd", "zcx");
put("12", "09");
put("qq", "aa");
}};
List result = oldList.stream()
.map(line -> map.entrySet()
.stream()
.filter(entry -> line.startsWith(entry.getKey()))
.map(entry -> line.replace(entry.getKey(), entry.getValue()))
.collect(Collectors.toList())
)
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(result);
}
Following example produces output like:
[zcx-qwe, 093]
Suggested solution can be easily parallelized if needed. Functional approach with no side effects.