12/07/2018

[Java8] Function interface

Function interface has an abstract method "apply" which take argument of type T and must returns a result of type R.

Java definition

Represents a function that accepts one argument and produces a result.

public interface Function<T, R> {
    R apply(T t);
    ...
}

Here are some test cases.
Applies this function to the given argument.

    @Test
   public void testFuncApply()
   {
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Assertions.assertEquals(Integer.valueOf(100), sqrt.apply(10));
   }

A composed function that first applies the function to its input, and then applies this to the result.

 @Test
   public void testFuncCompose()
   {
      //given
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Function<String, Integer> input = sqrt.compose(((s) -> Integer.parseInt(s)));
      //when
      Integer result = input.apply("9");
      //verify
      Assertions.assertEquals(Integer.valueOf(81), result);
   }

A composed function that first applies this function to its input and the applies the function to the result.

   public void testFuncAndThen()
   {
      //given
      Function<Integer, Integer> sqrt = (num) -> num * num;
      Function<Integer, Integer> times = sqrt.andThen((num) -> num * num);
      Function<String, Integer> input = times.compose(((s) -> Integer.parseInt(s)));

      //when
      Integer result = input.apply("10");

      //verify
      Assertions.assertEquals(Integer.valueOf(10000), result);
   }

A function that always returns its input argument.

   @Test
   public void testIdentity()
   {
      //given
      Map<String, String> result =
         Arrays.asList("a", "b", "c")
            .stream()
            .collect(Collectors.toMap(Function.identity(), str -> str));
      //verify
      Assertions.assertTrue(result.size() == 3);
      Assertions.assertEquals(result.get("a"), "a");
      Assertions.assertEquals(result.get("b"), "b");
      Assertions.assertEquals(result.get("c"), "c");
   }

No comments:

Post a Comment