Lambda Expressions - Hello World

原创转载请注明出处:http://agilestyle.iteye.com/blog/2375461

CitiesTest.java

imperative way

declarative way

package chapter1;

import java.util.Arrays;
import java.util.List;

public class CitiesTest {
    private static void findShanghaiImperative(final List<String> cityList) {
        boolean flag = false;
        for (String city : cityList) {
            if (city.equals("Shanghai")) {
                flag = true;
                break;
            }
        }

        System.out.println("Found Shanghai?: " + flag);
    }

    private static void findShanghaiDeclarative(final List<String> cityList) {
        System.out.println("Found Shanghai?: " + cityList.contains("Shanghai"));
    }

    public static void main(String[] args) {
        List<String> cityList = Arrays.asList("Shanghai", "Beijing", "Guangzhou", "Shenzhen");

        findShanghaiImperative(cityList);
        findShanghaiDeclarative(cityList);
    }
}

Console Output


 

PricesTest.java

imperative way

declarative way

package chapter1;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

public class PricesTest {
    private static final List<BigDecimal> priceList = Arrays.asList(
            new BigDecimal("10"), new BigDecimal("30"), new BigDecimal("17"),
            new BigDecimal("20"), new BigDecimal("15"), new BigDecimal("18"),
            new BigDecimal("45"), new BigDecimal("12"));

    private static void discountImperative(final List<BigDecimal> priceList) {
        BigDecimal totalOfDiscountedPrices = BigDecimal.ZERO;

        for (BigDecimal price : priceList) {
            if (price.compareTo(BigDecimal.valueOf(20)) > 0) {
                totalOfDiscountedPrices = totalOfDiscountedPrices.add(price.multiply(BigDecimal.valueOf(0.9)));
            }
        }

        System.out.println("Total of discounted prices: " + totalOfDiscountedPrices);
    }

    private static void discountDeclarative(final List<BigDecimal> priceList) {
        BigDecimal totalOfDiscountedPrices = priceList.stream().filter(price -> price.compareTo(BigDecimal.valueOf(20)) > 0)
                .map(price -> price.multiply(BigDecimal.valueOf(0.9)))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        System.out.println("Total of discounted prices: " + totalOfDiscountedPrices);
    }

    public static void main(String[] args) {
        discountImperative(priceList);
        discountDeclarative(priceList);
    }
}

Console Output


 

Reference

Pragmatic.Functional.Programming.in.Java.Mar.2014

猜你喜欢

转载自agilestyle.iteye.com/blog/2375461
今日推荐