Friday, June 13, 2014

Java 8 : Frequently Asked Questions for Interview - 3

What is Lambda Expression?
Lamdba expressions are just a block of code that can be passed around, which can be executed later, once or multiple times. A detailed answer here

Follow-up Question - Where have you seen similar code blocks in Java all along, before Java 8?

There are several examples where you write code in Java at some point, and it is executed at a later time. However, since Java is Object Oriented language, its not easy to pass or give somebody a block of code without having to construct an object belonging to a class that has the method with the desired behavior ( the method is the only behavior we want to execute ).
  1. run Method of a Runnable : while working with separate threads, we put the work in run method of a Runnable. Which we either execute by constructing an instance of the class that implements Runnable or simply submit the instance to a thread pool to start it in queue.
  2. class Task implements Runnable {
        public void run() {
            for(int i = 0; i < 10 ; i++) doTask(); 
        }
    }
    
    Task task = new Task();
    new Thread(w).start();
    
  3. sorting with custom comparator :while primitive sorts can work without any custom comparator code, sometimes the need arises to sort values based on different criteria. For instance  sorting an array of car objects, based on first their color, or their ratings or based on their prices. One can construct separate comparators and pass it to Array.sort method to defer the sorting at runtime. Note: the current code works with Java7 which has static method Integer.compare implemented in core java library.
  4. class ColorComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return firstCar.getColor().compareTo(secondCar.getColor()); 
        }
    }
    class RatingComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return Float.compare(firstCar.getRatings(),secondCar.getRatings());
        }
    }
    
    class PriceComparator implements Comparator<Car> {
        public int compare(Car firstCar, Car secondCar) {
            return Integer.compare(firstCar.getPrice(),secondCar.getPrice());
        }
    }
    
    
    Car cars = new Car[] { new Car("blue", 5.2f, 12000), new Car("green", 5.1f, 200000), new Car("grey", 6.2f, 1000), new Car("blue", 5.25f, 12090)}
    Arrays.sort(cars, newColorComparator());
    Color Cars
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ green, 5.1 200000 ]
    Car [ grey, 6.2 1000 ]
    
    Arrays.sort(cars, new RatingComparator());
    Ratings Cars
    Car [ green, 5.1 200000 ]
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ grey, 6.2 1000 ]
    
    Arrays.sort(cars, new PriceComparator());
    Price Cars
    Car [ grey, 6.2 1000 ]
    Car [ blue, 5.2 12000 ]
    Car [ blue, 5.25 12090 ]
    Car [ green, 5.1 200000 ]
    
    
  5. button callback : Button callback is another example of deferred execution. A callback action added to a class implementing the listener interface is a good example of that sort. For button, we can construct an instance of the class implementing the listener interface and then register it to the button class. In fact, the strategy is used often for creating GUI component callback actions the most listeners use "anonymous instance of the anonymous class".
  6. button.setOnAction(new EventHandler<actionEvent>() {
        public void handle(ActionEvent event) {
            System.out.Println("Event registered with User's click!!!")
        }
    }
    
    
    The callback is executed only on the click of the button, which eventually calls the code inside the handle method.
NOTE : It is possible to work with blocks of code in directly in other languages, However, in those languages it is vary easy to spawn a thread or to register a button click handler. In java, one could accomplish similar goals by writing similar API, but such API would be very unpleasant to use.

No comments:

Post a Comment