Streams on Strings
Completed
Read a sentence. Using streams print: the distinct words in lower case, sorted, joined by commas; and the average word length with 2 decimals.
Input
One line.
Output
Two lines.
Example
Input
The cat saw the Dog and the CAT
Output
and,cat,dog,saw,the 3.00
Editor
Java
Hints
distinct() removes duplicates; sorted() sorts.
Collectors.joining(",") joins strings.
Solution explanation
average() returns an OptionalDouble because an empty stream has no average.
Show solution
import java.util.Arrays;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] words = sc.nextLine().trim().split("\\s+");
String distinct = Arrays.stream(words)
.map(String::toLowerCase)
.distinct()
.sorted()
.collect(Collectors.joining(","));
double avg = Arrays.stream(words).mapToInt(String::length).average().orElse(0);
System.out.println(distinct);
System.out.printf("%.2f%n", avg);
}
}