首页 > 解决方案 > 在 Java 中运行 Stream.map() 内部的函数?

问题描述

我想映射一个字符串数组,如果其中一个包含 x 例如,做一些事情,但是,我不知道怎么做。如果有人可以帮助我,那将不胜感激。顺便说一句,这是一个示例代码:

public static void test(String s) {
    if (s.contains("h")) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }

    String example = Arrays.stream(example)
        .map(s -> {
            test(s);
        })
        .collect(Collectors.toList())
        .toString();
}

标签: javalambdajava-stream

解决方案


  1. 您不能对输出String和从中创建流的数组使用相同的名称 ( example)。使用String[] input = {"hello", "world"};然后流式传输String example = Arrays.stream(input)...
  2. map方法需要一个Function<T,R>. 该方法void test(String s)与它不兼容,因为它的返回类型。它应该返回String或根本不使用map
  3. 您一次想要很多东西并将它们混合在一起。你想得到结果然后打印出来吗?或者你想单独打印出每个结果而不收集任何东西?或者两者兼而有之 - 立即打印并收集它们?

以下代码段包含您可能需要的所有案例:

public static String test(String s) {
    return s.contains("h") ? "Yes" : "No";
}
String[] input = {"hello", "world"};

String example = Arrays.stream(input)  // Streaming "hello" and "world"
    .map(s -> test(s))                 // Converting each word to a result ("Yes" or "No")
    .peek(s -> System.out.println(s))  // Printing the result out immediatelly
    .collect(Collectors.toList())      // Collecting to List<String>
    .toString();

System.out.println(example);       // Prints [Yes, No]

几点注意事项:

  • map(s -> test(s))应使用方法引用重写:map(YourClass::test)

  • peek(s -> System.out.println(s))也应重写:(peek(System.out::println)

  • 收集到 a 的更好方法Stringcollect(Collectors.joining(", "))

    • Yes, No

推荐阅读