woensdag 10 februari 2016

Lambda en Anonymous classes in Java

package testpack;

import java.util.List;

public interface ListMethods {
    List<String> SortFruits(List<String> original);
}


package testpack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class testlambda {

    public List<String> StrategyTest(ListMethods strategy) {
        List<String> fruits = Arrays.asList("Apple", "Tomato", "Currant", "Cranberry");
        return strategy.SortFruits(fruits);
    }
   
    public List<String> getFuitsAnotherWay() {
        ListMethods anonymMethods = new ListMethods() {
            public List<String> SortFruits(List<String> original) {
                Collections.sort(original);
                return original;
            }
        };
        return StrategyTest(anonymMethods); 
    }   

    public List<String> getFuitsAnotherWayLambda() {
        return StrategyTest((fruitList) -> {
            Collections.sort(fruitList);
            return fruitList;
        });
    }   
   
    public static void main(String[] args) {
       
        List<String> result;
       
        result = new ArrayList<String>();       
        result.add("hallo");
        result.add("nederland");
       
        result.stream()
                 .filter(x -> x != "nederland")
                 .forEach(x -> {
                     System.out.println(x);
                 });
       
        testlambda tl = new testlambda();
        result = tl.getFuitsAnotherWayLambda();
        for (String s: result) {
            System.out.println(s);
        }
       
        System.exit(-1);
    }

}

Geen opmerkingen:

Een reactie posten