1

I tried to read on the new java.util.function Consumer, Supplier and Function.

I didn't understand why do we need them, what was the problem and what they solved?

Could you please give me an example of use without those API and with the new API and what is solved?

user1365697
  • 5,819
  • 15
  • 60
  • 96
  • 3
    Do you mean the 2 interfaces `Consumer` and `Supplier`? If so, did you read their JavaDocs? And did you read about lambdas? – Thomas Jul 26 '16 at 11:02
  • Yes I meant 2 interfaces Consumer and Supplier I read the javadocs but I didn't understand why they solved – user1365697 Jul 26 '16 at 11:04
  • 3
    They are common [functional interfaces](http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html#package.description) intended to be used as targets for [lambda expressions](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html). – Jesper Jul 26 '16 at 11:07
  • @ Jesper- what do you meant targets for lambda expression ? – user1365697 Jul 26 '16 at 11:09

1 Answers1

4

Perhaps you assume that they have to be more complex than they are.

They are designed to be super simple pieces of code which don't do very much in themselves, but as pieces of code you can pass to a library which can use these pieces of code.

This example prints 100 UUIDs using a Supplier and a Consumer

Stream.generate(UUID::random) // <<< Supplier<UUID>
      .limit(100)
      .forEach(System.out::println); // <<< Consumer<UUID>

A longer example is

Supplier<UUID> uuidSupplier = UUID::random;
Consumer<UUID> uuidConsumer = System.out::println;
Stream.generate(uuidSupplier)
      .limit(100)
      .forEach(uuidConsumer);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 2
    sorry but I didn't understand how the supplier and consumer is explained in this example – user1365697 Jul 26 '16 at 11:15
  • 3
    @user1365697 A `Supplier` solves the problem of when you need to be able to tell a library how to create an object as required and a `Consumer` solves the problem of telling a library about an action you want to perform for each object. – Peter Lawrey Jul 26 '16 at 11:18
  • if I don't use Supplier and Consumer how the example should look like ? in the example you didn't use them so I little bit confused – user1365697 Jul 26 '16 at 11:27
  • 2
    @user1365697 I think I see the problem, I did use them, perhaps the longer example helps. – Peter Lawrey Jul 26 '16 at 11:32