Java8 Lambda Expressions 学习案例

 关于Java8 Lambda Expressions,市面已有比较丰富的学习案例,本文章纯粹为学习笔记,话不多说,直接上代码。

Java8 Lambda Expressions 学习案例

package com.zacktest.lambda;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.IntBinaryOperator;
import java.util.function.IntSupplier;
import java.util.function.Predicate;

import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;

/**
 * Java8 Lambda Expressions学习案例
 * @author Zack
 * @version 1.0
 * @date 2018/8/14
 */
public class LambdaTest {

    public static void main(String[] args) {
        testFunInterface();
        testForEach();
        testRunable();
        testComparator();
        testStream();
    }

    /**
     * 常用的函数式接口
     */
    private static void testFunInterface() {
        System.out.println("---------------------------- cutting line---------------------------");
        IntSupplier intSupplier = () -> 5;
        System.out.println(intSupplier.getAsInt());

        Consumer<String> stringConsumer = (String s) -> System.out.println(s);
        stringConsumer.accept("test string");

        IntBinaryOperator intBinaryOperator = (int x, int y) -> x + y;
        System.out.println(intBinaryOperator.applyAsInt(10, 20));
    }

    /**
     * 使用Lambda简化集合的操作
     */
    private static void testForEach() {
        System.out.println("---------------------------- cutting line---------------------------");
        String[] atp = {"Jenk Cheng", "Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer"};
        List<String> players = Arrays.asList(atp);

        for (String player : players) {
            System.out.print(player + "; ");
        }

        // Using lambda expression and functional operations
        players.forEach((player) -> System.out.print(player + "; "));

        // Using double colon operator in Java 8
        players.forEach(System.out::println);
    }

    /**
     * 使用Lambda简化线程的操作
     */
    private static void testRunable() {
        System.out.println("---------------------------- cutting line---------------------------");
        // Using anonymous innerclass
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello world 1!");
            }
        }).start();

        // Using lambda expression
        new Thread(() -> System.out.println("Hello world 2!")).start();

        // Using anonymous innerclass
        Runnable race1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello world 3!");
            }
        };

        // Using lambda expression
        Runnable race2 = () -> System.out.println("Hello world 4!");

        // Run em!
        race1.run();
        race2.run();
    }

    /**
     * 使用Lambda简化比较器的操作
     */
    private static void testComparator(){
        System.out.println("---------------------------- cutting line---------------------------");
        String[] players = {"Jenk Cheng", "Rafael Nadal", "Novak Djokovic", "Stanislas Wawrinka", "David Ferrer", "Roger Federer", "Andy Murray", "Tomas Berdych", "Juan Martin Del Potro", "Richard Gasquet", "John Isner"};

        // Sort players by name using anonymous innerclass
        Arrays.sort(players, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return (s1.compareTo(s2));
            }
        });

        // Sort players by name using lambda expression
        Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));

        Arrays.sort(players, sortByName);
        // or this
        Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));
    }

    /**
     * java8流式操作集合、对象
     * 支持快速排序、过滤、统计、并行处理等操作
     */
    private static void testStream(){
        System.out.println("---------------------------- cutting line---------------------------");
        List<Person> javaProgrammers = new ArrayList<Person>() {
            {
                add(new Person("Maude", "Jaimie", "Java programmer", "female", 27, 1900));
                add(new Person("Shawn", "Randall", "Java programmer", "male", 30, 2300));
                add(new Person("Elsdon", "Jaycob", "Java programmer", "male", 43, 2000));
                add(new Person("Tamsen", "Brittany", "Java programmer", "female", 23, 1500));
                add(new Person("Floyd", "Donny", "Java programmer", "male", 33, 1800));
                add(new Person("Sindy", "Jonie", "Java programmer", "female", 32, 1600));
                add(new Person("Vere", "Hervey", "Java programmer", "male", 22, 1200));
                add(new Person("Palmer", "Dene", "Java programmer", "male", 33, 2000));
                add(new Person("Addison", "Pam", "Java programmer", "female", 34, 1300));
                add(new Person("Jayden", "Corrina", "Java programmer", "female", 35, 1700));
            }
        };

        List<Person> phpProgrammers = new ArrayList<Person>() {
            {
                add(new Person("Victor", "Channing", "PHP programmer", "male", 32, 1600));
                add(new Person("Tori", "Sheryl", "PHP programmer", "female", 21, 1000));
                add(new Person("Alvin", "Lance", "PHP programmer", "male", 38, 1600));
                add(new Person("Osborne", "Shad", "PHP programmer", "male", 32, 1100));
                add(new Person("Jarrod", "Pace", "PHP programmer", "male", 34, 1550));
                add(new Person("Evonne", "Shari", "PHP programmer", "female", 40, 1800));
                add(new Person("Clarette", "Cicely", "PHP programmer", "female", 23, 1200));
                add(new Person("Rosalind", "Layla", "PHP programmer", "female", 25, 1300));
                add(new Person("Fraser", "Hewie", "PHP programmer", "male", 36, 1100));
                add(new Person("Quinn", "Tamara", "PHP programmer", "female", 21, 1000));
            }
        };

        // Define some filters
        Predicate<Person> ageFilter = (p) -> (p.getAge() > 25);
        Predicate<Person> salaryFilter = (p) -> (p.getSalary() > 1400);
        Predicate<Person> genderFilter = (p) -> ("female".equals(p.getGender()));

        // Reuse filters
        System.out.println("Show female Java programmers older than 24 years:");
        javaProgrammers.stream()
                .filter(ageFilter)
                .filter(genderFilter)
                .forEach((p) -> System.out.println(p.getFirstName() + "," + p.getLastName()));

        System.out.println("Sort and show the first 5 Java programmers by name:");
        List<Person> sortedJavaProgrammers = javaProgrammers
                .stream()
                .sorted((p, p2) -> (p.getFirstName().compareTo(p2.getFirstName())))
                .limit(5)
                .collect(toList());
        sortedJavaProgrammers.forEach(System.out::println);

        System.out.println("Sort and show Java programmers by salary:");
        sortedJavaProgrammers = javaProgrammers
                .stream()
                .sorted((p, p2) -> (p.getSalary() - p2.getSalary()))
                .collect(toList());
        sortedJavaProgrammers.forEach(System.out::println);

        System.out.println("Get PHP programmers first name to String:");
        String phpDevelopers = phpProgrammers
                .stream()
                .map(Person::getFirstName)
                .collect(joining(" ; "));
        System.out.println(phpDevelopers);

        System.out.println("Get Java programmers last name to TreeSet:");
        TreeSet<String> javaDevLastName = javaProgrammers
                .stream()
                .map(Person::getLastName)
                .collect(toCollection(TreeSet::new));
        javaDevLastName.forEach(System.out::println);

        System.out.println("Streams can also be parallel. An example is below:");
        System.out.println("Calculate total money spent for paying Java programmers:");
        int totalSalary = javaProgrammers
                .parallelStream()
                .mapToInt(p -> p.getSalary())
                .peek(System.out::println)
                .sum();
        System.out.println("totalSalary:" + totalSalary);

        System.out.println("Get count, min, max, sum, and average from person salary:");
        IntSummaryStatistics stats = javaProgrammers
                .parallelStream()
                .mapToInt(p -> p.getSalary())
                .summaryStatistics();
        System.out.println("Max salary in stats : " + stats.getMax());
        System.out.println("Lowest salary in stats : " + stats.getMin());
        System.out.println("Sum of all numbers : " + stats.getSum());
        System.out.println("Average of all numbers : " + stats.getAverage());
    }
}
package com.zacktest.lambda;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author Zack
 * @version 1.0
 * @date 2018/8/14
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
    private String firstName;
    private String lastName;
    private String job;
    private String gender;
    private int salary;
    private int age;
}

说明:以上测试案例均源于国外这篇文章

http://www.jguru.com/article/core/start-using-java-lambda-expressions.html

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HiiZack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值