简体   繁体   English

在 Java 中的 Stream.map() 内运行 function?

[英]Run a function inside of Stream.map() in Java?

I want to map through an array of strings, and if one of them contains x for example, do something, however, I can't figure out how.我想通过一个字符串数组 map ,如果其中一个包含 x 例如,做一些事情,但是,我不知道怎么做。 If someone could help me, that would be appreaciated.如果有人可以帮助我,那将不胜感激。 Btw, here is an example code:顺便说一句,这是一个示例代码:

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();
}
  1. You cannot use the same name for the output String and an array from which a stream is created ( example ).您不能对 output String和从中创建 stream 的数组使用相同的名称( example )。 Use String[] input = {"hello", "world"};使用String[] input = {"hello", "world"}; and then stream that String example = Arrays.stream(input)...然后 stream String example = Arrays.stream(input)...
  2. The map method expects a Function<T,R> . map方法需要一个Function<T,R> The method void test(String s) is not compatible with it because of its return type.方法void test(String s)与它不兼容,因为它的返回类型。 It should either return String or don't use map at all.它应该要么返回String ,要么根本不使用map
  3. You want many things at once and mix them up.您一次想要很多东西并将它们混合在一起。 Do you want to get the results and then print them out?你想得到结果然后打印出来吗? Or do you want to print out each result individually and not collect anything at all?或者你想单独打印出每个结果而不收集任何东西? Or both - immediate print out and collecting them?或者两者兼而有之——立即打印出来并收集它们?

The following snippet contains all the cases you might want:以下代码段包含您可能需要的所有案例:

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]

Few notes:几点注意事项:

  • map(s -> test(s)) shall be rewritten using a method reference: map(YourClass::test) map(s -> test(s))应使用方法引用重写: map(YourClass::test)

  • peek(s -> System.out.println(s)) shall be rewritten as well: ( peek(System.out::println) peek(s -> System.out.println(s))也应重写:( peek(System.out::println)

  • A better way of collecting to a String is collect(Collectors.joining(", ")) that results in:收集到String的更好方法是collect(Collectors.joining(", ")) ,它会导致:

    • Yes, No

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM