Final answer:
The Java program provided covers all four steps for processing a text file using Java stream processing to filter out non-numeric and non-positive numbers, calculate averages, identify the overall average, and then extract values significantly higher than the average.
Step-by-step explanation:
The task is to write a program using Java stream processing to filter, process, and display data from a text file. Initially, each line of the file, which consists of four positive double values, is to be read and split into an array. Only numeric, positive values should be retained. Step 1 requires filtering out non-numeric and non-positive numbers, resulting in a list of arrays of valid Doubles. Step 2 involves computing and collecting the averages of these arrays into a new list, and Step 3 requires calculating the overall average of these averages. Finally, Step 4 filters the averages list to include only those more than 25% above the overall average, effectively identifying the highest averages.
Here is the Java code encompassing all four steps:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamProcessor {
public static void main(String[] args) throws Exception {
// Step 1
List list = Files.lines(Paths.get("Input2.txt"))
.map(line -> line.split("\\s+"))
.filter(arr -> Arrays.stream(arr).allMatch(s -> s.matches("\\d+(\\.\\d+)?")))
.map(arr -> Arrays.stream(arr).map(Double::valueOf).toArray(Double[]::new))
.filter(arr -> Arrays.stream(arr).allMatch(d -> d > 0))
.collect(Collectors.toList());
list.forEach(arr -> System.out.println("List contains: " + Arrays.toString(arr)));
// Step 2
List averages = list.stream()
.map(arr -> Arrays.stream(arr).mapToDouble(Double::doubleValue).average().orElse(0))
.collect(Collectors.toList());
averages.forEach(a -> System.out.printf("%.2f%n", a));
// Step 3
double sum = averages.stream().reduce(0.0, Double::sum);
long count = averages.stream().count();
double overallAverage = sum / count;
System.out.printf("Overall average: %.2f%n", overallAverage);
// Step 4
double threshold = overallAverage * 1.25;
List highestAverages = averages.stream()
.filter(a -> a > threshold)
.collect(Collectors.toList());
System.out.print("Highest averages: ");
highestAverages.forEach(a -> System.out.printf("%.2f%n", a));
}
}