Home > Software engineering >  Is it possible to define a Java Function or BiFunction w/o lambda expression?
Is it possible to define a Java Function or BiFunction w/o lambda expression?

Time:09-24

In Java, I have only ever defined "method references" Function and BiFunction w/ lambda expressions, like so:

    private static Function<Integer, Boolean> IsEvenFunc =
            (i) -> (i % 2 == 0);
    private static BiFunction<String, Character, Boolean> ByFirstCharFunc =
            (s, c) -> (s.charAt(0) == c.charValue());
    CustomList<Integer> numbers = new CustomList<>();
    numbers.append(9);
    numbers.append(42);
    numbers.append(47);
    System.out.println(numbers.toStringBy(IsEvenFunc));

    CustomList<String> names = new CustomList<>();
    names.append("Joe");
    names.append("Jim");
    names.append("Bob");
    System.out.println(names.toStringBy(ByFirstCharFunc, 'J'));

However, for teaching purposes, if my students don't yet know lambda syntax, is it possible to create these Function and BiFunction methods without lambda expressions?

Something like...?

   private static BiFunction<String s, Character c, Boolean> ByFirstCharFunc
   {
        return s.charAt(0) == c.charValue();
   }

CodePudding user response:

You could always just define it as a regular function/method like this:

private static boolean IsEven(int i){
    return i % 2 == 0;
}

private static boolean FirstChar(String s, char c){
    return s.charAt(0) == c;
}

CodePudding user response:

You can write a class which implements that interface:

class MatchFirstChar implements Function<String,Boolean> {
  private final char c;
  MatchFirstChar(char c) {
    this.c = c;
  }
  Boolean apply(String s) {
    return s.charAt(0) == c;
  } 
}

and then use it:

System.out.println(names.toStringBy(new MatchFirstChar('J')));

This is more verbose than any of the other ways of doing this, but I think it introduces the minimum of new concepts.

  • Related