Reputation: 21
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
Reputation: 44408
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)...
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.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