Convert an loop (while and for) to stream

Joe :

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 while and for loop to stream, but I'm not getting it right:

List<String> list = new ArrayList<>();
if (!oldList.isEmpty()) {// old is a List<String>
    Iterator<String> itr = oldList.iterator();
    while (itr.hasNext()) {
        String line = (String) itr.next();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (line.startsWith(entry.getKey())) {
         String newline = line.replace(entry.getKey(),entry.getValue());
                list.add(newline);
            }
        }
    }
}

I wanted to know if it's possible to convert the above example to a single stream where there is a while loop inside of a for loop.

Chris :

As was stated above, using streams here doesn't really add value since it makes the code harder to read/understand. I get that you're doing it more as a learning exercise. That being said, doing something like this is a slightly more functional-style approach as it doesn't have a side effect of adding to the list from within the stream itself:

list = oldList.stream().flatMap(line->
            map.entrySet().stream()
                    .filter(e->line.startsWith(e.getKey()))
                    .map(filteredEntry->line.replace(filteredEntry.getKey(),filteredEntry.getValue()))
        ).collect(Collectors.toList());

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458855&siteId=1