Search code examples
javajava-streamsummary

You can extend the IntSummaryStatistics class?


I'm using the Java stream statistics, using the speedment, this way:

IntSummaryStatistics intSummary = join.stream(). MapToInt (t> t.get0(). GetCNationkey ()). SummaryStatistics();
Long sumResult = intSummary.getSum ();

I wanted a new class to construct a new getSum() method. Something like:

IntSummaryStatisticsTest intSummarytest = join.stream (). MapToInt (t> t.get0 (). GetCNationkey ()). SummaryStatistics ();
Long sumResult = intSummarytest.getSumTest();

I tried to create a new class:

public class IntSummaryStatisticsTest extends IntSummaryStatistics {}

IntSummaryStatisticsTest summa = join.stream().mapToInt(t->t.get0().getCNationkey()).summaryStatistics();

but I got this error: incompatible types required java. Required: IntSummaryStatisticsTest Found: java.util.IntSummaryStatistics.

Is it possible to implement this new getSumTest() method?


Solution

  • Like I stated in the comments, I'd opt for composition over inheritance. This means that you can create your class, IntSummaryStatisticsTest, and accept an IntSummaryStatistics object as a parameter in your constructor. Your class would look something like the following:

    class IntSummaryStatisticsTest {
        private final IntSummaryStatistics statistics;
    
        public IntSummaryStatisticsTest(IntSummaryStatistics statistics) {
            this.statistics = statistics;
        }
    
        public long getSumTest() {
            // return your value
        }
    }
    

    The usage of the class would look like:

    var summary = new IntSummaryStatisticsTest(join.stream()
            .mapToInt(t -> t.get0().getCNationkey())
            .summaryStatistics());
    
    System.out.println(summary.getSumTest());