6

I am new to Java 8 features and this may be a stupid question but I am stuck at this point.

I am trying to run following code in eclipse but it gives compile time error.

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
import ch.lambdaj.Lambda;

public class LambdajTest {

    public static void main(String[] args) {

        List list = new ArrayList();
        list.add(1);
        list.add(3);
        list.add(8);
        list.add(10);
        list.add(16);

        int sum = list.stream().filter(p -> p > 10).mapToInt(p -> p).sum();
    }

}

Error is :- p cannot be resolved to a variable. I have added lambdaj 2.3.3 jar at classpath.

Kindly provide solution. Thanks in advance.

Tagir Valeev
  • 87,515
  • 18
  • 194
  • 305
  • You need to declare p as int in the lambda expression – ryekayo Mar 24 '16 at 18:59
  • 2
    Your code does not need LambdaJ. LambdaJ is mainly a library that provides nice collection methods and is targeted to Java < 8. It has nothing to do with Java 8 Lambdas. – Stefan Birkner Mar 27 '16 at 20:49

1 Answers1

5

The problem is that the JVM doesn't know what kind of object p is as you're using a raw collection.

Change

List list = new ArrayList();

to

List<Integer> list = new ArrayList<>();

The JVM now understands that it's streaming over a collection of Integer objects.

tddmonkey
  • 19,324
  • 9
  • 53
  • 66