|
| 1 | +package language; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | +import java.util.function.Consumer; |
| 7 | +import java.util.function.Function; |
| 8 | +import java.util.function.Supplier; |
| 9 | + |
| 10 | +/** |
| 11 | + * Created by hdhamee on 6/13/16. |
| 12 | + */ |
| 13 | +public class Java8MethodReferences { |
| 14 | + |
| 15 | + public static void main(String[] args) { |
| 16 | + |
| 17 | + // Suppliers is a function interface and represents a function that accepts no arguments and produce |
| 18 | + // a result of some arbitrary type. |
| 19 | + |
| 20 | + //Supplier referencing a constructor method: |
| 21 | + Supplier<User> userSupplierConstructor = User::new; |
| 22 | + User user1 = userSupplierConstructor.get(); |
| 23 | + |
| 24 | + //Supplier referencing a static method: |
| 25 | + Supplier<User> userSupplierStatic = UserFactory::produceUserStatic; |
| 26 | + User user2 = userSupplierStatic.get(); |
| 27 | + |
| 28 | + //Supplier Referencing a instance method: |
| 29 | + UserFactory userFactory = new UserFactory(); |
| 30 | + Supplier<User> userSupplierInstance = userFactory::produceUser; |
| 31 | + User user3 = userSupplierInstance.get(); |
| 32 | + |
| 33 | + //Consumers represent a function that accepts a single argument of an arbitrary type and produce no result |
| 34 | + |
| 35 | + // consumer using lambda expression |
| 36 | + Consumer<User> userConsumerLambda = (u) -> System.out.println("Username: " + u.getUsername()); |
| 37 | + userConsumerLambda.accept(user3); |
| 38 | + |
| 39 | + // consumer using method referencing |
| 40 | + Consumer<User> userConsumerMth = UserFactory::printName; |
| 41 | + userConsumerMth.accept(user3); |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + //referencing a static method |
| 47 | + List<Double> numbers = Arrays.asList(4.0, 9.0, 16.0, 25.0, 36.0); |
| 48 | + List<Double> squaredNumbers = Java8MethodReferences.findSquareRoot(numbers,Double::new); |
| 49 | + System.out.println("Square root of numbers = "+squaredNumbers); |
| 50 | + } |
| 51 | + |
| 52 | + private static List findSquareRoot(List list, Function<Double, Double> f){ |
| 53 | + List<Double> result = new ArrayList<>(); |
| 54 | + list.forEach( x -> result.add(f.apply(Math.sqrt((Double) x)))); |
| 55 | + return result; |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | + static class UserFactory { |
| 60 | + public User produceUser() { |
| 61 | + return new User(); |
| 62 | + } |
| 63 | + |
| 64 | + public static User produceUserStatic() { |
| 65 | + return new User(); |
| 66 | + } |
| 67 | + |
| 68 | + public static void printName(User user){ |
| 69 | + System.out.println(user.getUsername()); |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + static class User { |
| 74 | + public String getUsername(){ |
| 75 | + return "hari ram"; |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments