Convert an loop (while and for) to stream

前端 未结 4 1556
北海茫月
北海茫月 2021-01-05 00:33

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

4条回答
  •  清歌不尽
    2021-01-05 00:58

    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.

提交回复
热议问题