-1

I have an assignment in my CS class to write an anonymous and lambda function to replace the provided methods. I wrote the anonymous class fine but when trying to write the lambda function I am getting stuck on Syntax error on token "return", invalid (. Can anybody help me figure out the error message? I know it has to be something little that I forgot. Code Screenshot

I tried to create a lambda fuction to use a pre-determined function that checks for an odd number and updates a counter for the amount of odd numbers.

Error Message: Syntax error on token "return", invalid (Java(1610612971)

import java.util.*;

interface UnaryPredicate<T> {
   public boolean test(T obj);
}

final class Algorithm {
   public static <T> int countIf(Collection<T> c, UnaryPredicate<T> p) {
      int count = 0;
      for (T elem : c)
         if (p.test(elem))
            ++count;
         return count;
       }
    }

class OddPredicate implements UnaryPredicate<Integer> {
   public boolean test(Integer i) {
      return i % 2 != 0;
   }
}

class test {
   public static void main(String[] args) {
  Collection<Integer> ci = Arrays.asList(1, 2, 3, 4);

  int count1 = Algorithm.countIf(ci, new OddPredicate() {
     public boolean test(Integer i) {
        return i % 2 != 0;
     }
  });
     
  System.out.println("Number of odd integers = " + count1); 

  int count2 = Algorithm.countIf(ci, new OddPredicate().test = (Integer i) -> return i % 2 != 0); 
   }
}

1 Answers1

-1

First of all, out of the question, in your 'Algorithm' class body, the 'for' block is illegal i think , your version is

for (T elem : c)
     if (p.test(elem))
        ++count;
     return count;

It's well-advised to do that with following

for (T elem : c){
     if (p.test(elem))
        ++count;
     return count;
}

Back to the question, actually, you can just convey the lambda function , here is the correct one

int count2 = Algorithm.countIf(ci,  (Integer i) -> i % 2 != 0);