Lambda功能案例

LambdaDemo

	直接上代码
package sun.framework.genesis.beta.lambda;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: Administrator
 * @Date: 2019/7/31 15:18
 * @Description:
 * () -> {}代码块替代了整个匿名类
 * 使用lambda表达式对列表进行迭代
 * Java 8中使用lambda表达式的Map和Reduce示例(遍历修改)
 * 通过过滤创建一个String列表
 * 将字符串换成大写并用逗号链接起来
 * 本例展示了如何利用流的 distinct() 方法来对集合进行去重。
 * 计算集合元素的最大值、最小值、总和以及平均值
 */
public class LambdaDemo {

    /**
     * 功能描述:
     * runnable实现方法
     * () -> {}代码块替代了整个匿名类
     * (params) -> expression
     * (params) -> statement
     * (params) -> { statements }
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void AnonymousClassDemo() {
        /*jdk1.7*/
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Before Java8, too much code for too little to do");
            }
        }).start();
        /*jdk1.8*/
        new Thread(() -> System.out.println("In Java8, Lambda expression rocks !!")).start();


        List<String> list = Arrays.asList("I", "love", "you", "too");
        /*jdk1.7*/
        Collections.sort(list, new Comparator<String>() {// 接口名
            @Override
            public int compare(String s1, String s2) {// 方法名
                if (s1 == null)
                    return -1;
                if (s2 == null)
                    return 1;
                return s1.length() - s2.length();
            }
        });
        /*jdk1.8*/
        Collections.sort(list, (s1, s2) -> {// 省略参数表的类型
            if (s1 == null)
                return -1;
            if (s2 == null)
                return 1;
            return s1.length() - s2.length();
        });
    }


    /**
     * 功能描述:
     * 使用lambda表达式对列表进行迭代
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void ForEachDemo() {
        List<String> features = Arrays.asList("Lambdas", "Default Method", "Stream API", "Date and Time API");
        /*jdk1.7*/
        for (String feature : features) {
            System.out.println(feature);
        }
        /*jdk1.8*/
        features.forEach(n -> System.out.println(n));

        features.forEach(System.out::println);
    }

    /**
     * 功能描述:
     * Java 8中使用lambda表达式的Map和Reduce示例
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void ForEachMapDemo() {
        List<Map<String, Integer>> mapList = new ArrayList<>();
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("cost", 100);
        Map<String, Integer> map2 = new HashMap<>();
        map2.put("cost", 200);
        mapList.add(map1);
        mapList.add(map2);

        List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
        /*jdk1.7*/
        for (Integer cost : costBeforeTax) {
            double price = cost + .12 * cost;
            System.out.println(price);
        }
        /*jdk1.8*/
        /*单独修改*/
        mapList.stream().map((cost) -> cost.get("cost") + .12 * cost.get("cost")).forEach(System.out::println);
        costBeforeTax.stream().map((cost) -> cost + .12 * cost).forEach(System.out::println);
        /*修改后添加*/
        double bill = costBeforeTax.stream().map((cost) -> cost + .12 * cost).reduce((sum, cost) -> sum + cost).get();
        System.out.println("Total : " + bill);
    }

    /**
     * 功能描述:
     * 通过过滤创建一个String列表
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void ForEachStringFilterDemo() {
        List<String> strList = Arrays.asList("controller", "controller", "testtest", "controller", "testtesttest");
        List<String> filtered = strList.stream().filter(x -> x.length() > 6).collect(Collectors.toList());
        System.out.printf("Original List : %s, filtered list : %s %n", strList, filtered);
    }

    /**
     * 功能描述:
     * 对列表的每个元素应用函数
     * 将字符串换成大写并用逗号链接起来
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void ForEachStringMethodDemo() {
        List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.", "Canada");
        String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
        System.out.println(G7Countries);
    }

    /**
     * 功能描述:
     * 复制不同的值,创建一个子列表
     * 本例展示了如何利用流的 distinct() 方法来对集合进行去重。
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void ForEachDistinctMethodDemo() {
        List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);
        List<Integer> distinct = numbers.stream().map(i -> i * i).distinct().collect(Collectors.toList());
        System.out.printf("Original List : %s,  Square Without duplicates : %s %n", numbers, distinct);
    }

    /**
     * 功能描述:
     * 计算集合元素的最大值、最小值、总和以及平均值
     *
     * @param: []
     * @return: void
     * @auther: Administrator
     * @date: 2019/8/26 13:36
     */
    private static void ForEachMethodDemo() {

        List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
        IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
        System.out.println("Highest prime number in List : " + stats.getMax());
        System.out.println("Lowest prime number in List : " + stats.getMin());
        System.out.println("Sum of all prime numbers : " + stats.getSum());
        System.out.println("Average of all prime numbers : " + stats.getAverage());
    }


    public static void main(String[] args) {
        AnonymousClassDemo();
        ForEachDemo();
        ForEachMapDemo();
        ForEachStringFilterDemo();
        ForEachStringMethodDemo();
        ForEachDistinctMethodDemo();
        ForEachMethodDemo();
    }


}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页