Junior — Middle
Is it possible to create a custom operation for processing data streams within an existing system?
sobes.tech AI
Answer from AI
Yes, in Java, you can create your own stream operations by extending the Stream API capabilities. This can be done by implementing your own Collector, which defines how to gather stream elements into a final structure.
Example of creating a simple collector that joins elements into a string separated by commas:
import java.util.stream.Collector;
import java.util.stream.Collectors;
Collector<String, ?, String> joiningWithComma = Collectors.joining(", ");
// Usage:
List<String> list = Arrays.asList("apple", "banana", "cherry");
String result = list.stream().collect(joiningWithComma);
System.out.println(result); // Outputs: apple, banana, cherry
You can also create your own classes implementing the Collector interface for more complex logic.