JetBrains Academy: Map and flatMap - Kamil-Jankowski/Learning-JAVA GitHub Wiki
Maximum of the absolute values:
For a given array, output the maximum of absolute values in the array. Try not to use the for loop, but use Stream API.
Use .getAsInt()
to convert from OptionalInt
(returned by .max()
) to int.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int max = Arrays.stream(scanner.nextLine().split("\\s+"))
.mapToInt(Integer::parseInt)
.map(Math::abs)
.max()
.getAsInt();
System.out.println(max);
}
}
Sorting the absolute values:
For a given array, output the sorted array of absolute values. You should sort the array in the ascending order. Try not to use the for loop, but use Stream API.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Arrays.stream(scanner.nextLine().split("\\s+"))
.map(Integer::parseInt)
.map(Math::abs)
.sorted()
.forEach(n -> System.out.print(n + " "));
}
}
Count words without repetitions:
For given lines with words, count the number of unique words ignoring case sensitivity.
The first line contains the number N - the next N lines contain words separated by a space.
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lines = Integer.parseInt(scanner.nextLine());
Set<String> uniqueWords = new HashSet<>();
Set<List<String>> linesOfWords = new HashSet<>();
for (int i = 0; i < lines; i++) {
linesOfWords.add(Arrays.stream(scanner.nextLine().split("\\s+"))
.map(String::toUpperCase)
.collect(Collectors.toList()));
}
uniqueWords = linesOfWords.stream()
.flatMap(List::stream)
.collect(Collectors.toSet());
System.out.println(uniqueWords.size());
}
}
or
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int lines = Integer.parseInt(scanner.nextLine());
long count = Stream.generate(() -> Arrays.stream(scanner.nextLine().split("\\s+")))
.limit(lines)
.flatMap(s -> s)
.map(String::toLowerCase)
.distinct()
.count();
System.out.println(count);
}
}