Calcopod
Calcopod

Reputation: 21

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. 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();
}

Upvotes: 0

Views: 3629

Answers (1)

Nikolas
Nikolas

Reputation: 44408

  1. You cannot use the same name for the output String and an array from which a stream is created (example). Use String[] input = {"hello", "world"}; and then stream that String example = Arrays.stream(input)...
  2. The map method expects a Function<T,R>. The method void test(String s) is not compatible with it because of its return type. It should either return String or don't use map at all.
  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)

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

  • A better way of collecting to a String is collect(Collectors.joining(", ")) that results in:

    • Yes, No

Upvotes: 2

Related Questions