Lambda表达式例子

转 Lambda表达式例子

1.Java8 新特性介绍

写java的同学对java8肯定知道 那么java8到底有哪些特性呢,总结如下:

Lambda表达式
函数式接口
Stream
Optional
Predicate
Function
Consumer
Filter
Map-Reduce
新的Date API

取id 列表

List<Integer> transactionsIds = transactions.parallelStream().
 filter(t -> t.getType() == Transaction.GROCERY).
 sorted(comparing(Transaction::getValue).reversed()).
 map(Transaction::getId).
 collect(toList());

最核心的当然是函数式编程了,写代码非常简单,请看下面详细例子介绍

2.Java8 lambda使用总结-结合实例介绍

很多同学一开始接触Java8可能对Java8 Lambda表达式有点陌生,下面我将结合实例介绍Java8的使用 并与Java7进行比较:

基础类

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Person {
    private int id;
    private String name;
    private String address;
}

1.List操作

public class ExampleList {
    private static List<String> items = new ArrayList<>();
    static {
        items.add("A");
        items.add("BC");
        items.add("C");
        items.add("BD");
        items.add("E");
    }
    public static void main(String[] args) {
        //Java8之前操作List
        for(String item:items){
            System.out.println(item);
        }
        //Java8 lambda遍历list
        items.forEach(c-> System.out.println(c));
        items.forEach(item->{
            if("C".equals(item)){
                System.out.println(item);
            }
        });
        System.out.println("--------");
        //先过滤
        items.stream().filter(s->s.contains("B")).forEach(c1-> System.out.println(c1));
    }
}

2.Map操作

public class ExampleMap {
    private static Map<String, Integer> items = new HashMap<>();
    static {
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);
    }
    public static void main(String[] args) {
        //Java8之前遍历是这样遍历map
        for(Map.Entry<String,Integer> entry:items.entrySet()){
            System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
        }
        //Java8遍历map
        items.forEach((key,value)-> System.out.println("key:" + key + " value:" + value));
    }
}

3.Groupingby操作

/**
 *
 *Java8 Collectors.groupingBy and Collectors.mapping example
 */
public class ExampleMapping {
    private static List<Person> personList = Lists.newArrayList();
    static {
        personList.add(Person.builder().id(10).address("apple").address("shanghai").build());
        personList.add(Person.builder().id(12).address("apple").address("wuhan").build());
        personList.add(Person.builder().id(16).address("apple").address("nanjing").build());
    }
    public static void main(String[] args) {
        //分组
        Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(c -> c.getAddress()));
        System.out.println(collect);
    }
}

4.List转换为Map

public class ExampleListConvertMap {
    private static List<Person> personList = Lists.newArrayList();
    static{
        personList.add(Person.builder().id(20).name("zhangsan").address("shanghai").build());
        personList.add(Person.builder().id(30).name("lisi").address("nanjing").build());
    }
    public static void main(String[] args) {
        //Java8 List转换Map
        Map<Integer,Person> map_ = personList.stream().collect(Collectors.toMap((key->key.getId()),(value->value)));
        map_.forEach((key,value)-> System.out.println(key + ":" + value));
        Map<Integer, Person> mappedMovies = personList.stream().collect(
            Collectors.toMap(Person::getRank, Person::getData));
    }
}

5.FilterMap操作

public class ExampleFilterMap {
    private static Map<Integer,String> map_ = Maps.newHashMap();
    static{
        map_.put(1, "linode.com");
        map_.put(2, "heroku.com");
        map_.put(3, "digitalocean.com");
        map_.put(4, "aws.amazon.com");
    }
    public static void main(String[] args) {
        //before java iterator map
        String result = null;
        for(Map.Entry<Integer,String> entry:map_.entrySet()){
            if("heroku.com".equals(entry.getValue())){
                result = entry.getValue();
            }
        }
        System.out.println("Before Java 8 :" + result);
        //Java8 Map->Stream->Filter->String
        result =  map_.entrySet().stream().
                filter(map->"heroku.com".equals(map.getValue()))
                .map(map->map.getValue())
                .collect(Collectors.joining());
        System.out.println("Java 8 :" + result);
       Map<Integer,String> collect =  map_.entrySet().stream()
                .filter(c->c.getKey()==2)
                .collect(Collectors.toMap(p->p.getKey(),p->p.getValue()));
        System.out.println(collect);
    }
}

6.Optional操作可以防止NullPointException

Optional<String> optional = Optional.of("hello");
System.out.println(optional.isPresent());//true
System.out.println(optional.get());//hello
System.out.println(optional.orElse("false"));
optional.ifPresent((s)-> System.out.println(s.charAt(0)));//h

7.给出一个详细的例子

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    private String name;
    private int salary;
    private String office;
}
public class ExampleEmployee {
    private static List<Employee> employeeList = Lists.newArrayList();
    static{
        employeeList.add(Employee.builder().name("Matt").salary(5000).office("New York").build());
        employeeList.add(Employee.builder().name("Steve").salary(6000).office("London").build());
        employeeList.add(Employee.builder().name("Carrie").salary(20000).office("New York").build());
        employeeList.add(Employee.builder().name("Peter").salary(7000).office("New York").build());
        employeeList.add(Employee.builder().name("Pat").salary(8000).office("London").build());
        employeeList.add(Employee.builder().name("Tammy").salary(29000).office("Shanghai").build());
    }
    public static void main(String[] args) {
        //anyMatch
        boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(isMatch);
        //返回所有salary大于6000
        boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>4000);
        System.out.println(matched);
        //找出工资最高
        Optional<Employee> hightestSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(hightestSalary);
        //返回姓名列表
        List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
        System.out.println(names);
        //List转换成Map
        Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
        employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
        //统计办公室是New York的个数
        long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("Shanghai")).count();
        System.out.println(officeCount);
        //List转换为Set
        Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
        System.out.println(officeSet);
        //查找办公室地点是New York的员工
        Optional<Employee> allMatchedEmployees = employeeList.stream().filter(employee -> employee.getOffice().equals("New York")).findAny();
        System.out.println(allMatchedEmployees);
        //按照工资的降序来列出员工信息
        List<Employee> sortEmployeeList =  employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
        //按照名字的升序列出员工信息
        List<Employee> sortEmployeeByName = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
        System.out.println(sortEmployeeList);
        System.out.println("按照名字的升序列出员工信息:" + sortEmployeeByName);
        //获取工资最高的前2条员工信息
        List<Employee> top2EmployeeList= employeeList.stream()
                .sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
                .limit(2)
                .collect(Collectors.toList());
        System.out.println(top2EmployeeList);
        //获取平均工资
        OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
        System.out.println("平均工资:" + averageSalary);
        //查找New York
        OptionalDouble averageSalaryByOffice = employeeList.stream().filter(employee -> employee.getOffice()
                .equals("New York"))
                .mapToInt(employee->employee.getSalary())
                .average();
        System.out.println("New York办公室平均工资:" + averageSalaryByOffice);
    }
}

8.Java8常见操作


public class EmployeeTest {
    public static List<Employee> generateData() {
        return Arrays.asList(new Employee("Matt", 5000, "New York"),
                new Employee("Steve", 6000, "London"),
                new Employee("Carrie", 10000, "New York"),
                new Employee("Peter", 7000, "New York"),
                new Employee("Alec", 6000, "London"),
                new Employee("Sarah", 8000, "London"),
                new Employee("Rebecca", 4000, "New York"),
                new Employee("Pat", 20000, "New York"),
                new Employee("Tammy", 9000, "New York"),
                new Employee("Fred", 15000, "Tokyo"));
    }
    public static Map<String, Integer> generateMapData() {
        Map<String, Integer> items = Maps.newHashMap();
        items.put("A", 10);
        items.put("B", 20);
        items.put("C", 30);
        items.put("D", 40);
        items.put("E", 50);
        items.put("F", 60);
        return items;
    }
    @Test
    public void testEmployee() {
        List<Employee> results = generateData();
        //打印出名字是Steve的员工信息
        results.forEach(c -> {
            if (c.getName().equals("Steve")) {
                System.out.println(c);
            }
        });
        System.out.println("---------");
        //找出年薪超过6000的员工
        results.stream().filter(c -> c.getSalary() >= 60000).forEach(c -> System.out.println(c));
        System.out.println("--->>>>>>----");
        //java8遍历map
        Map<String, Integer> map_ = generateMapData();
        map_.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
        System.out.println("---->>>>分组>>>-----");
        //java8 分组操作
        Map<String, List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
        System.out.println(groupMap);
        System.out.println("---->>>>List转化为Map>>>----");
        //List转化Map
        Map<String, Object> map = results.stream().collect(Collectors.toMap(Employee::getName, Employee::getOffice));
        map.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
        System.out.println("---->>>>>>>----");
        Map<Integer, Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()), (value -> value)));
        employeeMap.forEach((key, value) -> System.out.println(key + "," + value));
        System.out.println("---->>遍历map>>>----");
        //打印出值大于30的map
        Map<String, Integer> resultMap = map_.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
        resultMap.forEach((key, value) -> System.out.println(key + "=" + value));
        System.out.println(">>>>>>>>>>>>>>>");
        //打印key=D的map
        Map<String, Integer> mapResults = map_.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
        mapResults.forEach((key, value) -> System.out.println(key + ">>>>" + value));
        System.out.println(">>>>>>>Optional>>>>>>>");
        Optional<String> optional = Optional.of("hello");
        System.out.println(optional.isPresent());
    }
    @Test
    public void testEmployeeExample() {
        //anyMatch
        List<Employee> employeeList = generateData();
        boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(isMatch);
        //allMatch
        boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
        System.out.println(matched);
        //找出工资最高的
        Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employeeOptional);
        //找出工资最少的
        Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
        System.out.println(employee);
        //返回姓名列表
        List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
        System.out.println(names);
        System.out.println(">>>>>>>>>>>");
        //List转化Map
        Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
        employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
        //统计办公室是New York的个数
        long officeCount =  employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
        System.out.println(officeCount);
        long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
        System.out.println(salaryCount);
        //List转化为Set
        Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
        System.out.println(officeSet);
        Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
        System.out.println(salarySet);
        //查找办公室地点是New York的员工
        Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
        System.out.println(optionals);
        System.out.println(">>>>>工资降序排序>>>>>");
        //按照工资的降序来列出员工信息
        List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
        System.out.println(sortSalaryEmployeeList);
        System.out.println(">>>>>姓名升序排序>>>>>");
        List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
        System.out.println(sortNameEmployeeList);
        System.out.println(">>>>获取工资最高的前2条员工信息");
        List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
        System.out.println(dispaly2EmployeeList);
        System.out.println(">>>>获取平均工资");
        OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
        System.out.println(averageSalary);
        System.out.println(">>>>获取工作地点的平均工资");
        OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
        System.out.println(optionalDouble);
        System.out.println(">>>>>>Java8 Optional用法>>>>>>");
        Optional<String> stringOptional = Optional.of("test");
        System.out.println(stringOptional.get());
        Optional<String> isOptional = Optional.ofNullable("hello");
        System.out.println(isOptional.isPresent());
        System.out.println(isOptional.get());
        System.out.println(isOptional.orElse("0"));
        System.out.println(">>>>>>>>>>>>");
        //Optional<String> optionalVal = Optional.of(null);
        // System.out.println(optionalVal);
        Optional<String> optional = Optional.ofNullable("optional");
        System.out.println(optional);
        System.out.println(optional.isPresent());
        System.out.println(optional.get());
        System.out.println(optional.orElse("haha"));
        System.out.println(">>>>>>>>>>>>");
        Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
        System.out.println(employeeOptional_);
    }
}

时间: 2024-10-12 08:11:30

Lambda表达式例子的相关文章

C++11 Lambda表达式简单解析

C++11 新增了很多特性,lambda 表达式是其中之一,如果你想了解的 C++11 完整特性, 建议去http://www.open-std.org/看看新标准! 很多语言都提供了 lambda 表达式,如 Python,Java 8 lambda 表达式可以方便地构造匿名函数,如果你的代码里面存在大量的小函数,而这些函数一般只被调用一次,那么不妨将他们重构成 lambda 表达式. C++11 的 lambda 表达式规范如下: [ capture ] ( params ) mutable

【Java学习笔记之三十一】详解Java8 lambda表达式

Java 8 发布日期是2014年3月18日,这次开创性的发布在Java社区引发了不少讨论,并让大家感到激动.特性之一便是随同发布的lambda表达式,它将允许我们将行为传到函数里.在Java 8之前,如果想将行为传入函数,仅有的选择就是匿名类,需要6行代码.而定义行为最重要的那行代码,却混在中间不够突出.Lambda表达式取代了匿名类,取消了模板,允许用函数式风格编写代码.这样有时可读性更好,表达更清晰.在Java生态系统中,函数式表达与对面向对象的全面支持是个激动人心的进步.将进一步促进并行

Python中的Lambda表达式小析

Lambda表达式在Python中经常使用到,在此总结下Lambda表达式的常用方法. 首先,要明白Lambda表达在Python中是作为一个匿名函数的构造器而存在.其次,要明白Lambda表达式的常用场景是Lambda表达式对应函数的使用次数非常有限(因此,没有必要专门定义一个非匿名函数),同时保证了代码的简洁性. 最简单的一个Lambda表达式例子和对应的非匿名函数: f = lambda x: x + 1 print ( f(1) ) def h (x): return x + 1 pri

C++11 lambda 表达式解析

C++11 新增了很多特性,lambda 表达式是其中之一,如果你想了解的 C++11 完整特性,建议去这里,这里,这里,还有这里看看.本文作为 5 月的最后一篇博客,将介绍 C++11 的 lambda 表达式. 很多语言都提供了 lambda 表达式,如 Python,Java 8.lambda 表达式可以方便地构造匿名函数,如果你的代码里面存在大量的小函数,而这些函数一般只被调用一次,那么不妨将他们重构成 lambda 表达式. C++11 的 lambda 表达式规范如下: [ capt

Java8 lambda表达式10个示例

本文由 ImportNew Java 8 刚于几周前发布,日期是2014年3月18日,这次开创性的发布在Java社区引发了不少讨论,并让大家感到激动.特性之一便是随同发布的lambda表达式,它将允许我们将行为传到函数里.在Java 8之前,如果想将行为传入函数,仅有的选择就是匿名类,需要6行代码.而定义行为最重要的那行代码,却混在中间不够突出.Lambda表达式取代了匿名类,取消了模板,允许用函数式风格编写代码.这样有时可读性更好,表达更清晰.在Java生态系统中,函数式表达与对面向对象的全面

动态生成C# Lambda表达式

转载:http://www.educity.cn/develop/1407905.html,并整理! 对于C# Lambda的理解我们在之前的文章中已经讲述过了,那么作为Delegate的进化使用,为了让代码简洁和优雅的呈现,C# Lambda表达式的使用功不可灭,那么依托外部条件如何动态构建C# Lambda表达式呢.下面让我们来具体的看看实施. 或许你会奇怪这个需求是如何产生的…… 首先,Lambda 在 DLinq 中承担了以往 T-SQL 的部分角色:其次,在数据库设计中,我们往往需要依

Java 8 Lambda表达式10个示例【存】

PS:不能完全参考文章的代码,请参考这个文件http://files.cnblogs.com/files/AIThink/Test01.zip 在Java 8之前,如果想将行为传入函数,仅有的选择就是匿名类,需要6行代码.而定义行为最重要的那行代码,却混在中间不够突出.Lambda表达式取代了匿名类,取消了模板,允许用函数式风格编写代码.这样有时可读性更好,表达更清晰.在Java生态系统中,函数式表达与对面向对象的全面支持是个激动人心的进步.将进一步促进并行第三方库的发展,充分利用多核CPU.尽

Lambda表达式详解(例子详解)(转自:http://blog.csdn.net/damon316/article/details/51734661)

Lambda表达式详解(例子详解) lambda简介 lambda运算符:所有的lambda表达式都是用新的lambda运算符 " => ",可以叫他,"转到"或者 "成为".运算符将表达式分为两部分,左边指定输入参数,右边是lambda的主体. lambda表达式: 1.一个参数:param=>expr 2.多个参数:(param-list)=>expr 上面这些东西,记着,下面我们开始应用并阐述lambda,让你乐在其中.

java8 Lambda表达式的10个例子(转)

原文:http://jobar.iteye.com/blog/2023477 Java8中Lambda表达式的10个例子 例1 用Lambda表达式实现Runnable接口 Java代码 收藏代码//Before Java 8: new Thread(new Runnable() { @Override public void run() { System.out.println("Before Java8, too much code for too little to do");