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));
   }

1 comment:

  1. Anonymous1/12/22 16:31

    Fourth on our listing is Fortune Jack, a web-based website with one thing for everyone. There is no devoted cell app, 점보카지노 but the website is fully optimized for smaller screens. To prime it all off, there’s also a devoted part for Bitcoin games. As soon as you add new names, words, locations, manufacturers and update the wheel a new new} share URL shall be generated. It will show up within the textual content field underneath the 'Update' button. Either copy the URL manually or click on the 'Copy wheel' button.

    ReplyDelete