【问题标题】:Java stream modifying stringsJava流修改字符串
【发布时间】:2021-10-04 21:01:16
【问题描述】:

我想请你们帮助我使用 fp 修改我的字符串列表。我是流 api 新手,有一些基本知识,但无法解决此任务。我有三个字符串列表,每个字符串都包含我的原始语言的电影标题和英文翻译,然后每个字符串列表都会映射。我想达到的结果是,我从用“>”分隔的列表中打印电影,然后当它切换到另一个列表时,我想放置“|”。例如: Zelazny czlowiek>钢铁侠|Msciciele>复仇者联盟|Blyskawica>闪电侠

   public Map<String, List<String>> getMovies() {
    List<String> ironManTranslations = new ArrayList<>();
    ironManTranslations.add("Żelazny Człowiek");
    ironManTranslations.add("Iron Man");

    List<String> avengersTranslations = new ArrayList<>();
    avengersTranslations.add("Mściciele");
    avengersTranslations.add("Avengers");

    List<String> flashTranslations = new ArrayList<>();
    flashTranslations.add("Błyskawica");
    flashTranslations.add("Flash");

    Map<String, List<String>> booksTitlesWithTranslations = new HashMap<>();
    booksTitlesWithTranslations.put("IM", ironManTranslations);
    booksTitlesWithTranslations.put("AV", avengersTranslations);
    booksTitlesWithTranslations.put("FL", flashTranslations);

    return booksTitlesWithTranslations;
}

public void printMovies(){

    getMovies().values().stream().flatMap(movie -> movie.stream().map(s -> s + ">")).forEach(System.out::print);

}

【问题讨论】:

    标签: java functional-programming java-stream


    【解决方案1】:

    您可以使用map 运算符为每个列表创建翻译对。然后使用 joining 收集器将它们加入列表之间,使用 |操作员。这是它的外观。

    String mStr = booksTitlesWithTranslations.values().stream()
        .map(l -> l.get(0) + ">" + l.get(1))
        .collect(Collectors.joining("|"));
    

    【讨论】:

    • 现在似乎很容易。非常感谢您的帮助,我一定会记住这一点,以便将来完成类似的任务。
    • 任意列表大小而不是固定两个的一般解决方案是.map(l -&gt; String.join("&gt;", l))
    • 我什至不知道。感谢您告知我们。
    猜你喜欢
    • 2021-06-14
    • 2010-12-14
    • 1970-01-01
    • 2017-09-26
    • 2014-05-30
    • 2018-04-10
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多