'How to collect Strings read from file into a custom class using collect from Streams
I have a custom class State
public class State {
private double sum;
private int count;
public void inc(double d){
sum+=d;
count++;
}
public void add(State s){
this.sum+=s.sum;
this.count+=s.count;
}
public double average(){
return sum/count;
}
}
And I have a tester class for that class:
import java.io.*;
import java.util.Arrays;
import java.util.function.*;
import java.util.stream.*;
import java.nio.file.*;
public class StateTest {
public static void main(String[] a) throws IOException{
BiConsumer<State,Double> acc = (s,d)->s.inc(d);
BiConsumer<State,State> comb = (s,s1)->s.add(s1);
Stream<String> ss = Files.lines(Path.of(a[0]));
//double avg = ss.mapToDouble(Double::valueOf).filter(b -> b <= 42.0f && b >= -42.0f).collect(//Dont know what to write here).average()
}
}
for which I want to do the following:
Read out lines of doubles from a text file, convert them into Doubles, and collect them using .collect(Supplier, Accumulator, Combiner) method.
I am having trouble writing the supplier for State class. I don't also clearly get the meaning of this kind of .collect() and what does it mean to supply? I have to collect it into the State and then call .average() of the State function to get the average of the double.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
