簡體   English   中英

使用Java Stream多次處理結果

[英]Process the result multiple times using Java Stream

如何在以下代碼中將for-loop部分轉換為Java Stream?

    Map<String, String> attributes = new HashMap() {{
        put("header", "Hello, world!");
        put("font", "Courier New");
        put("fontSize", "14px");
        put("color", "#0000ff");
        put("content", "hello, world" +
                "");
    }};
    Path templatePath = Paths.get("C:/workspace/spring-boot-demos/something.tpl");
List<String> lines = Files.readAllLines(templatePath).stream()
                .filter(Objects::nonNull)
                .map(line -> {
                    String parsedLine = "";
                    for (int i = 0; i < attributes.size(); i++) {
                        if (parsedLine.equals("")) parsedLine = this.parse(attributes, line);
                        else parsedLine = this.parse(attributes, parsedLine);
                    }

                    return parsedLine;
                })
                .collect(Collectors.toList());

public String parse(Map<String, String> attributes, String line) {
        return attributes.entrySet().stream()
                .filter(attributeMap -> line.indexOf("{{" + attributeMap.getKey() + "}}") != -1)
                .map(attributeMap -> {
                    String attributeKey = attributeMap.getKey();
                    String attributeValue = attributeMap.getValue();
                    String newLine = line.replace("{{" + attributeKey + "}}", attributeValue);
                    return newLine;
                })
                .findFirst().orElse(line);
    }

我發現很難以Java 8 Stream方式實現它,因此我不得不執行舊的for-loop構造。 其背后的原因是,對於字符串的每一行,可能會有一個或多個占位符(使用{{}}分隔符)。 我有值列表( attributesHashMap )來替換它們。 我想確保在Stream循環離開每一行之前,所有占位符都必須替換為Map的值。 無需執行此操作,僅替換第一個占位符。

謝謝。

更新:這是something.tpl文件的內容:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>HTML Generator</title>
        <style>
            body {
                font-family: "{{font}}";
                font-size: {{fontSize}};
                color: {{color}};
            }
        </style>
    </head>
    <body>
        <header>{{header}}</header> {{content}}
        <main>{{content}}</main>
        <h1>{{header}}</h1>
    </body>
</html>

因此,您要替換給定列表中的每個標記嗎?

這是我對流進行的操作:

  1. 遍歷行
  2. 每行僅解析一次
  3. 解析遍歷屬性,並替換當前屬性

如果您丟失了String[] pLine可能是...

package so20190412;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Snippet {

    public Snippet() {
    }

    public static void main(String[] args) {        

        Map<String, String> attributes = new HashMap<String, String> () {{
            put("john", "doe");
            put("bruce", "wayne");
        }};
        List<String> lines = Arrays.asList("My name is {{john}}, not {{bruce}}.", "Hello, {{john}}!", "How are you doing?");

        new Snippet().replaceAll(attributes, lines).forEach(System.out::println);

    }

    public List<String> replaceAll(Map<String, String> attributes, List<String> lines) {
        return lines.stream().map(l -> parse(attributes, l)).collect(Collectors.toList());
    }

    public String parse(Map<String, String> attributes, String line) {
        String[] pLine = {line};
        attributes.entrySet().stream()
                .forEach(attr -> {
                    String attributeKey = attr.getKey();
                    String attributeValue = attr.getValue();
                    String newLine = pLine[0].replace("{{" + attributeKey + "}}", attributeValue);
                    pLine[0] = newLine;
                });
        return pLine[0];
    }
}

不要猶豫,問一下您是否不了解某些內容。

HTH!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM