12/07/2018

[Java8] Consumer Functional Interface

From wikipedia

A consumer is a person or organization that use economic services or commodities.

The consumer is the one who pays something to consume goods and services produced. As such, consumers play a vital role in the economic system of a nation. Without consumer demand, producers would lack one of the key motivations to produce: to sell to consumers. The consumer also forms part of the chain of distribution.

From Java definition

Represent an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, is expected to operate via side-effects.

Its main functional name is "accept", but why not call "consume" method. Does it mean consumer only accepts the input argument to consume?

Here are some test cases.
Performs this operation on the given argument.

  @Test
   public void testConsumerAccept()
   {
      //given
      List<String> names = new ArrayList();
      Consumer<String> addStudent = (name) -> names.add(name);
      //when
      addStudent.accept("chris");
      //verify
      Assertions.assertEquals("chris", names.get(0));
   }

A composed consumer that performs, in sequence, this operation followed by the code after operation

   public void testConsumerAcceptAndThenPrint()
   {
      //given
      List<String> names = new ArrayList();
      Consumer<String> addStudent = (name) -> names.add(name);
      Consumer<String> printStudentAfterAdding = addStudent.andThen(name -> System.out.println("added " + name));
      //when
      printStudentAfterAdding.accept("chris");
      //verify
      Assertions.assertEquals("chris", names.get(0));
   }

No comments:

Post a Comment