Reduce a stream to a single value. Count the integers with mapToInt...sum, then turn them back into a comma-separated string with collect...joining. Two different reductions, one source.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List nums = Arrays.asList(1, 2, 3, 4);
int sum = nums.stream().mapToInt(Integer::intValue).sum();
String joined = nums.stream().map(String::valueOf)
.collect(Collectors.joining(","));
System.out.println(sum);
System.out.println(joined);
}
}
Before you run it, say out loud what it will print. Then open the answer.
What it prints
10
1,2,3,4
sum is an int-typed terminal that folds to a primitive, while joining collects to a String. Pick the terminal that matches the result you want.