One-liner: Extracting Long Statistics From A Collection of POJOs

From a collection of objects representing method calls:


public class MethodCall {

    private String methodName;
    private int duration;

    public MethodCall(String methodName, int duration) {
        this.methodName = methodName;
        this.duration = duration;
    }

    public String getMethodName() {
        return methodName;
    }

    public int getDuration() {
        return duration;
    }
}

useful statistics data can be extracted with Collectors.summarizingLong:


import java.util.ArrayList;
import java.util.LongSummaryStatistics;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;

public class LongSummaryStatisticsTest {

    private ArrayList<MethodCall> calls;

    @Before
    public void provideTestData() {
        this.calls = new ArrayList<>();
        calls.add(new MethodCall("save", 90));
        calls.add(new MethodCall("find", 10));
        calls.add(new MethodCall("delete", 2));

    }

    @Test
    public void computeStatistics() {

        LongSummaryStatistics statistics = this.calls.stream().
                collect(Collectors.summarizingLong(MethodCall::getDuration));

        assertThat(statistics.getCount(), is(3l));
        assertThat(statistics.getMin(), is(2l));
        assertThat(statistics.getMax(), is(90l));
        assertThat(statistics.getAverage(), is(34d));
        assertThat(statistics.getSum(), is(102l));
    }

}


The code above was extracted from "Effective Java EE" online course (coming soon), the second part of the Java EE Bootstrap at parleys.com.

See you at Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License