Transform values with a stream
The goal is to transform an array of numbers into a comma-delimited string using functional programming. The code snippet you provided has a minor issue: String.join(",", strings[0])
is incorrect because it tries to join a single element (strings[0]
) rather than all elements in the strings
array.
Here's the corrected code for the transformValues
method:
import java.util.Arrays;
class Answer {
// Change these boolean values to control whether you see
// the expected answer and/or hints.
static boolean showExpectedResult = true;
static boolean showHints = true;
// Transform an array of numbers into a comma-delimited list
// using functional programming.
static String transformValues(int[] numbers) {
// Convert the int array to a stream of integers
// Map each integer to its String representation
// Collect the results into a String array
String[] strings = Arrays.stream(numbers)
.mapToObj(String::valueOf)
.toArray(String[]::new);
// Join the array of strings into a single comma-delimited string
return String.join(",", strings);
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String result = transformValues(numbers);
System.out.println(result); // Output: 1,2,3,4,5
}
}
Explanation
Convert Array to Stream: Arrays.stream(numbers) Converts the
int[]
array to anIntStream
.Map to String: mapToObj(String::valueOf) Maps each
int
in the stream to itsString
representation usingString::valueOf
.Collect to Array: .toArray(String[]::new) Collects the results into a
String[]
array.Join Strings: String.join(",", strings) Joins all elements of the
String[]
array into a singleString
, with each element separated by a comma.
Comments
Post a Comment