0

I have following code to generate summary for the list of values(Integer for this example). When I use method reference to get the values it is failing at run time giving ArrayIndexOutOfBoundException, but supplier is working fine.

static void test1() {

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stWorking = intList.stream().collect(Collectors.summarizingInt(num -> num));
System.out.println(stWorking);

IntSummaryStatistics stRuntimeError = intList.stream().collect(Collectors.summarizingInt(intList::get));
System.out.println(stRuntimeError);

}

Can somebody please help to understand what is the reason for this?

Thanks.

Chota Bheem
  • 1,106
  • 1
  • 13
  • 31
  • 2
    `intList::get` when the element is 2 is bound to blow up. Read the linked question. – Tunaki Apr 19 '16 at 09:44
  • The linked answer explains ArrayIndexOutOfBoundsException but I am not accessing the list/array by the index. I am trying to understand what's the reason that the code with Method Ref doesn't work but the supplier function works. I tried with more elements but its still failing. – Chota Bheem Apr 19 '16 at 09:49
  • 1
    Yes, yes you are. `intList::get` can be written `num -> intList.get(num)`. So when `num = 2`: BOOM. (or `num = 5` with your edit) – Tunaki Apr 19 '16 at 09:50
  • 1
    Oh now I get it. Thanks. – Chota Bheem Apr 19 '16 at 09:52

0 Answers0