Home > Back-end >  CircularFifoBuffer .avg() calculation fails
CircularFifoBuffer .avg() calculation fails

Time:03-01

I have the following dummy code which saves a list of doubles in a hasmap to a specific key, I want to be able to use this buffer to calculate average values over each key.

    final int bufferSize = 5;

    HashMap<Integer, List<Double>> testmap = new HashMap<Integer, List<Double>>();

    List<Double> Values1 = Arrays.asList(1.1,2.2,3.3,4.4,5.5,6.6,7.7,8.8,9.9);
    List<Double> Values2 = Arrays.asList(22.2,33.3,44.4,55.5,66.6,77.7,88.8,99.9);
    List<Double> Values3 = Arrays.asList(333.3,444.4,555.5,666.6);

    testmap.put(123456, Values1);
    testmap.put(234567, Values2);
    testmap.put(345678, Values3);

    HashMap<Integer, CircularFifoBuffer> buffer = new HashMap<Integer, CircularFifoBuffer>();

    for (Map.Entry<Integer, List<Double>> entry: testmap.entrySet()) {
        Integer key = entry.getKey();
        List<Double> value = entry.getValue();
        CircularFifoBuffer bufferEntries = new CircularFifoBuffer(4);

        for(Double val : value){
            bufferEntries.add(val);
        }

        buffer.put(key, bufferEntries);
    }

I now want to calculate a simple average

buffer.get(345678).stream().mapToDouble(d -> d).average().orElse(0.0)

Which returns "incompatible types: bad return type in lambda expression, cannot be converted to Double. I tried without the maptoDOuble but then I do not get the avg() method. ANyone any idea why this won't work

CodePudding user response:

CircularFifoBuffer is not generic, it use the fixed Object type:

public boolean add(Object element)

then, you must to specify the exact source type since Object could be any type. If you write

buffer.get(345678).stream().mapToDouble(d -> (Double) d).average().orElse(0.0)
                                              ^^^^^^

your code compile and produce the expected output

499.95000000000005

a good reading might be The Basics of Java Generics.

  • Related