Unique Words from Lines (flatMap)
Problem
Each input line has words separated by spaces. Print all different words, one per line, in alphabetical order. Ignore the case: print the words in small letters.
Constraints
- 1 <= lines <= 10^4
Examples
Input
Hello world hello Java
Output
hello java world
Solutions
map gives one result for each input; flatMap gives a list for each input and joins the lists. That is why flatMap is the right tool when one line makes many words. JavaScript sort() on strings compares by code units, which is the same as alphabetical order for small letters.
/*
* Problem : Process lines.
* Input : Several lines.
* Output : The different words.
* Approach: flatMap, distinct, sorted.
* Time : O(n log n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
// Step 1: flatMap turns each line into a stream of words and joins all these streams into one stream.
// Step 2: map makes the words small letters, distinct removes repeated words, and sorted puts them in alphabetical order.
return java.util.Arrays.stream(lines)
.flatMap(line -> java.util.Arrays.stream(line.split("\\s+")))
.map(String::toLowerCase)
.distinct()
.sorted()
.toArray(String[]::new);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (1)
- What is the difference between map and flatMap?