Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an loop (while and for) to stream

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.

like image 695
Joe Avatar asked Aug 22 '17 14:08

Joe


People also ask

Can you convert a while loop to a for loop?

You can always convert a while loop to a for loop. The while loop and the do loop are equivalent in their expressive power; in other words, you can rewrite a while loop using a do loop, and vice versa. You can always write a program without using break or continue in a loop.

Is stream better than for loop?

If you have a small list, loops perform better. If you have a huge list, a parallel stream will perform better. Purely thinking in terms of performance, you shouldn't use a for-each loop with an ArrayList, as it creates an extra Iterator instance that you don't need (for LinkedList it's a different matter).

How do I iterate a stream?

List interface provides a stream() method which gives a stream to iterate using forEach method. In forEach method, we can use the lambda expression to iterate over all elements. The following code snippet shows the usage of streams to iterate over the list.

Do while loops java8?

Java do-while loop is used to execute a block of statements continuously until the given condition is true. The do-while loop in Java is similar to while loop except that the condition is checked after the statements are executed, so do while loop guarantees the loop execution at least once.


2 Answers

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());
like image 116
Chris Avatar answered Sep 21 '22 11:09

Chris


I don't see why you would want to use streams here, but it is possible.

Create some test input:

List<String> oldList = Arrays.asList("adda","bddb","cddc");
Map<String,String> map = new HashMap<>();
map.put("a", "x");
map.put("b", "y");
map.put("c", "z");

List<String> list = new ArrayList<>();

The actual code:

oldList.stream()
    .forEach(line -> map.entrySet().stream()
            .filter(entry -> line.startsWith(entry.getKey()))
            .forEach(entry -> list.add(line.replace(entry.getKey(),entry.getValue()))));

Print the outcome:

list.forEach(System.out::println);

Which is:

xddx
yddy
zddz
like image 36
Robin Topper Avatar answered Sep 21 '22 11:09

Robin Topper