Convert a loop (while and for) to a stream

I started working with Java 8 and tried to convert some loops and old syntax into my code in lambdas and threads.

So, for example, I am trying to convert this while for a loop to a stream, but I do not understand:

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 is possible to convert the above example into a single thread, where a while loop exists inside the for loop.

+4
source share
4 answers

, , /. , . , - , :

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());
+4

, , .

:

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<>();

:

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

:

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

:

xddx
yddy
zddz
+3

, 1-:

List<String> list = oldList.stream()
    .filter(line -> map.keySet().stream().anyMatch(line::startsWith))
    .map(line -> map.entrySet().stream()
        .filter(entry -> line.startsWith(entry.getKey()))
        .map(entry -> line.replace(entry.getKey(), entry.getValue()))
        .findFirst().get())
    .collect(Collectors.toList());
+3

, , oldList. oldList mapper, map, .

public static void main(String[] args) {
    final List<String> oldList = Arrays.asList("asd-qwe", "zxc", "123");
    final Map<String, String> map = new HashMap<String, String>() {{
        put("asd", "zcx");
        put("12", "09");
        put("qq", "aa");
    }};

    List<String> 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);
}

:

[zcx-qwe, 093]

The proposed solution can be easily parallelized, if necessary. Functional approach without side effects.

+1
source

Source: https://habr.com/ru/post/1684233/


All Articles