编程语言
首页 > 编程语言> > Java8 lambda 的使用

Java8 lambda 的使用

作者:互联网

Java8 lambda 的使用

1.Java8 新特性介绍

原文链接 https://my.oschina.net/chenxiaobian/blog/704421,https://www.cnblogs.com/hmdrzql/p/6354010.html

现在我们有一个需求:给一个user组成的list 按照user的年龄排序。实现不难,代码如下:

 UserCompare是一个实现了Comprator的类

这种方法由于sort方法的第二个参数是Comparator 所以你要写一个实现类(我这里是UserCompare类),并且override该接口的实现方法。

java8提供了lambda来简化,有了lambda程序员从此不加班呀~    

刚才那个Comparator的实现类以及内部若干代码就都省了,代之以lambda表达式。

另外,IntelliJ会提示你改成更好的写法

实现类里有多少代码,你就省了多少行代码。

高兴了半天,到底是什么原理呢?其实是java8新提供的语法糖。

我们打开java1.8 Comparator的定义,发现了类定义上面多了一个@FunctionalInterface

对,1.8多了一个概念就是FunctionalInterface,这个Comparator就是一个FunctionalInterface

有了这个注解,原来使用实现类的地方就可以代之以lambda表达式。

 

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

  1.   Lambda表达式
  2.    
  3.   函数式接口
  4.    
  5.   Stream
  6.    
  7.   Optional
  8.    
  9.   Predicate
  10.    
  11.   Function
  12.    
  13.   Consumer
  14.    
  15.   Filter
  16.    
  17.   Map-Reduce
  18.    
  19.   新的Date API

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

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

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

基础类

  1.   @Data
  2.   @Builder
  3.   @AllArgsConstructor
  4.   @NoArgsConstructor
  5.   public class Person {
  6.    
  7.   private int id;
  8.   private String name;
  9.   private String address;
  10.    
  11.    
  12.   }

1.List操作

  1.   public class ExampleList {
  2.   private static List<String> items = new ArrayList<>();
  3.    
  4.   static {
  5.   items.add("A");
  6.   items.add("BC");
  7.   items.add("C");
  8.   items.add("BD");
  9.   items.add("E");
  10.   }
  11.    
  12.   public static void main(String[] args) {
  13.   //Java8之前操作List
  14.   for(String item:items){
  15.   System.out.println(item);
  16.   }
  17.    
  18.   //Java8 lambda遍历list
  19.   items.forEach(c-> System.out.println(c));
  20.    
  21.   items.forEach(item->{
  22.   if("C".equals(item)){
  23.   System.out.println(item);
  24.   }
  25.   });
  26.    
  27.   System.out.println("--------");
  28.    
  29.   //先过滤
  30.   items.stream().filter(s->s.contains("B")).forEach(c1-> System.out.println(c1));
  31.    
  32.   }
  33.   }

2.Map操作

  1.   public class ExampleMap {
  2.    
  3.   private static Map<String, Integer> items = new HashMap<>();
  4.    
  5.   static {
  6.   items.put("A", 10);
  7.   items.put("B", 20);
  8.   items.put("C", 30);
  9.   items.put("D", 40);
  10.   items.put("E", 50);
  11.   items.put("F", 60);
  12.   }
  13.    
  14.   public static void main(String[] args) {
  15.    
  16.   //Java8之前遍历是这样遍历map
  17.   for(Map.Entry<String,Integer> entry:items.entrySet()){
  18.   System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
  19.   }
  20.    
  21.   //Java8遍历map
  22.   items.forEach((key,value)-> System.out.println("key:" + key + " value:" + value));
  23.    
  24.    
  25.   }
  26.    
  27.    
  28.   }

3.Groupingby操作

  1.   /**
  2.   *
  3.   *Java8 Collectors.groupingBy and Collectors.mapping example
  4.   */
  5.   public class ExampleMapping {
  6.    
  7.   private static List<Person> personList = Lists.newArrayList();
  8.    
  9.   static {
  10.   personList.add(Person.builder().id(10).address("apple").address("shanghai").build());
  11.   personList.add(Person.builder().id(12).address("apple").address("wuhan").build());
  12.   personList.add(Person.builder().id(16).address("apple").address("nanjing").build());
  13.   }
  14.    
  15.   public static void main(String[] args) {
  16.   //分组
  17.   Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(c -> c.getAddress()));
  18.   System.out.println(collect);
  19.   }
  20.   }

4.List转换为Map

  1.   public class ExampleListConvertMap {
  2.    
  3.   private static List<Person> personList = Lists.newArrayList();
  4.    
  5.   static{
  6.   personList.add(Person.builder().id(20).name("zhangsan").address("shanghai").build());
  7.   personList.add(Person.builder().id(30).name("lisi").address("nanjing").build());
  8.   }
  9.    
  10.   public static void main(String[] args) {
  11.   //Java8 List转换Map
  12.   Map<Integer,Person> map_ = personList.stream().collect(Collectors.toMap((key->key.getId()),(value->value)));
  13.   map_.forEach((key,value)-> System.out.println(key + ":" + value));
  14.    
  15.   Map<Integer, Person> mappedMovies = personList.stream().collect(
  16.   Collectors.toMap(Person::getRank, Person::getData));
  17.    
  18.   }
  19.   }

5.FilterMap操作

  1.   public class ExampleFilterMap {
  2.    
  3.   private static Map<Integer,String> map_ = Maps.newHashMap();
  4.    
  5.   static{
  6.   map_.put(1, "linode.com");
  7.   map_.put(2, "heroku.com");
  8.   map_.put(3, "digitalocean.com");
  9.   map_.put(4, "aws.amazon.com");
  10.   }
  11.    
  12.   public static void main(String[] args) {
  13.   //before java iterator map
  14.   String result = null;
  15.   for(Map.Entry<Integer,String> entry:map_.entrySet()){
  16.   if("heroku.com".equals(entry.getValue())){
  17.   result = entry.getValue();
  18.   }
  19.   }
  20.    
  21.   System.out.println("Before Java 8 :" + result);
  22.    
  23.   //Java8 Map->Stream->Filter->String
  24.   result = map_.entrySet().stream().
  25.   filter(map->"heroku.com".equals(map.getValue()))
  26.   .map(map->map.getValue())
  27.   .collect(Collectors.joining());
  28.   System.out.println("Java 8 :" + result);
  29.    
  30.   Map<Integer,String> collect = map_.entrySet().stream()
  31.   .filter(c->c.getKey()==2)
  32.   .collect(Collectors.toMap(p->p.getKey(),p->p.getValue()));
  33.   System.out.println(collect);
  34.    
  35.   }
  36.   }

6.Optional操作可以防止NullPointException

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

7.给出一个详细的例子

  1.   @Data
  2.   @Builder
  3.   @AllArgsConstructor
  4.   @NoArgsConstructor
  5.   public class Employee {
  6.    
  7.   private String name;
  8.   private int salary;
  9.   private String office;
  10.   }
  11.    
  12.    
  13.   public class ExampleEmployee {
  14.    
  15.   private static List<Employee> employeeList = Lists.newArrayList();
  16.    
  17.   static{
  18.   employeeList.add(Employee.builder().name("Matt").salary(5000).office("New York").build());
  19.   employeeList.add(Employee.builder().name("Steve").salary(6000).office("London").build());
  20.   employeeList.add(Employee.builder().name("Carrie").salary(20000).office("New York").build());
  21.   employeeList.add(Employee.builder().name("Peter").salary(7000).office("New York").build());
  22.   employeeList.add(Employee.builder().name("Pat").salary(8000).office("London").build());
  23.   employeeList.add(Employee.builder().name("Tammy").salary(29000).office("Shanghai").build());
  24.   }
  25.    
  26.   public static void main(String[] args) {
  27.   //anyMatch
  28.   boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
  29.   System.out.println(isMatch);
  30.    
  31.   //返回所有salary大于6000
  32.   boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>4000);
  33.   System.out.println(matched);
  34.    
  35.   //找出工资最高
  36.   Optional<Employee> hightestSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
  37.   System.out.println(hightestSalary);
  38.    
  39.   //返回姓名列表
  40.   List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
  41.   System.out.println(names);
  42.    
  43.   //List转换成Map
  44.   Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
  45.   employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
  46.    
  47.   //统计办公室是New York的个数
  48.   long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("Shanghai")).count();
  49.   System.out.println(officeCount);
  50.    
  51.   //List转换为Set
  52.   Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
  53.   System.out.println(officeSet);
  54.    
  55.   //查找办公室地点是New York的员工
  56.   Optional<Employee> allMatchedEmployees = employeeList.stream().filter(employee -> employee.getOffice().equals("New York")).findAny();
  57.   System.out.println(allMatchedEmployees);
  58.    
  59.   //按照工资的降序来列出员工信息
  60.   List<Employee> sortEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
  61.   //按照名字的升序列出员工信息
  62.   List<Employee> sortEmployeeByName = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
  63.   System.out.println(sortEmployeeList);
  64.   System.out.println("按照名字的升序列出员工信息:" + sortEmployeeByName);
  65.    
  66.   //获取工资最高的前2条员工信息
  67.   List<Employee> top2EmployeeList= employeeList.stream()
  68.   .sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
  69.   .limit(2)
  70.   .collect(Collectors.toList());
  71.   System.out.println(top2EmployeeList);
  72.    
  73.   //获取平均工资
  74.   OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
  75.   System.out.println("平均工资:" + averageSalary);
  76.    
  77.   //查找New York
  78.   OptionalDouble averageSalaryByOffice = employeeList.stream().filter(employee -> employee.getOffice()
  79.   .equals("New York"))
  80.   .mapToInt(employee->employee.getSalary())
  81.   .average();
  82.   System.out.println("New York办公室平均工资:" + averageSalaryByOffice);
  83.    
  84.   }
  85.   }

8.Java8常见操作

  1.    
  2.   public class EmployeeTest {
  3.    
  4.   public static List<Employee> generateData() {
  5.   return Arrays.asList(new Employee("Matt", 5000, "New York"),
  6.   new Employee("Steve", 6000, "London"),
  7.   new Employee("Carrie", 10000, "New York"),
  8.   new Employee("Peter", 7000, "New York"),
  9.   new Employee("Alec", 6000, "London"),
  10.   new Employee("Sarah", 8000, "London"),
  11.   new Employee("Rebecca", 4000, "New York"),
  12.   new Employee("Pat", 20000, "New York"),
  13.   new Employee("Tammy", 9000, "New York"),
  14.   new Employee("Fred", 15000, "Tokyo"));
  15.   }
  16.    
  17.   public static Map<String, Integer> generateMapData() {
  18.   Map<String, Integer> items = Maps.newHashMap();
  19.   items.put("A", 10);
  20.   items.put("B", 20);
  21.   items.put("C", 30);
  22.   items.put("D", 40);
  23.   items.put("E", 50);
  24.   items.put("F", 60);
  25.    
  26.   return items;
  27.   }
  28.    
  29.    
  30.   @Test
  31.   public void testEmployee() {
  32.   List<Employee> results = generateData();
  33.    
  34.   //打印出名字是Steve的员工信息
  35.   results.forEach(c -> {
  36.   if (c.getName().equals("Steve")) {
  37.   System.out.println(c);
  38.   }
  39.   });
  40.    
  41.   System.out.println("---------");
  42.    
  43.   //找出年薪超过6000的员工
  44.   results.stream().filter(c -> c.getSalary() >= 60000).forEach(c -> System.out.println(c));
  45.    
  46.   System.out.println("--->>>>>>----");
  47.    
  48.   //java8遍历map
  49.   Map<String, Integer> map_ = generateMapData();
  50.   map_.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
  51.    
  52.   System.out.println("---->>>>分组>>>-----");
  53.    
  54.   //java8 分组操作
  55.   Map<String, List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
  56.   System.out.println(groupMap);
  57.    
  58.   System.out.println("---->>>>List转化为Map>>>----");
  59.   //List转化Map
  60.   Map<String, Object> map = results.stream().collect(Collectors.toMap(Employee::getName, Employee::getOffice));
  61.   map.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
  62.    
  63.   System.out.println("---->>>>>>>----");
  64.   Map<Integer, Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()), (value -> value)));
  65.   employeeMap.forEach((key, value) -> System.out.println(key + "," + value));
  66.    
  67.   System.out.println("---->>遍历map>>>----");
  68.   //打印出值大于30的map
  69.   Map<String, Integer> resultMap = map_.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
  70.   resultMap.forEach((key, value) -> System.out.println(key + "=" + value));
  71.    
  72.   System.out.println(">>>>>>>>>>>>>>>");
  73.   //打印key=D的map
  74.   Map<String, Integer> mapResults = map_.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
  75.   mapResults.forEach((key, value) -> System.out.println(key + ">>>>" + value));
  76.    
  77.   System.out.println(">>>>>>>Optional>>>>>>>");
  78.   Optional<String> optional = Optional.of("hello");
  79.   System.out.println(optional.isPresent());
  80.    
  81.   }
  82.    
  83.   @Test
  84.   public void testEmployeeExample() {
  85.   //anyMatch
  86.   List<Employee> employeeList = generateData();
  87.   boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
  88.   System.out.println(isMatch);
  89.    
  90.   //allMatch
  91.   boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
  92.   System.out.println(matched);
  93.    
  94.   //找出工资最高的
  95.   Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
  96.   System.out.println(employeeOptional);
  97.    
  98.   //找出工资最少的
  99.   Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
  100.   System.out.println(employee);
  101.    
  102.   //返回姓名列表
  103.   List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
  104.   System.out.println(names);
  105.    
  106.   System.out.println(">>>>>>>>>>>");
  107.   //List转化Map
  108.   Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
  109.   employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
  110.    
  111.   //统计办公室是New York的个数
  112.   long officeCount = employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
  113.   System.out.println(officeCount);
  114.    
  115.   long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
  116.   System.out.println(salaryCount);
  117.    
  118.   //List转化为Set
  119.   Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
  120.   System.out.println(officeSet);
  121.    
  122.   Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
  123.   System.out.println(salarySet);
  124.    
  125.   //查找办公室地点是New York的员工
  126.   Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
  127.   System.out.println(optionals);
  128.    
  129.   System.out.println(">>>>>工资降序排序>>>>>");
  130.   //按照工资的降序来列出员工信息
  131.   List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
  132.   System.out.println(sortSalaryEmployeeList);
  133.    
  134.   System.out.println(">>>>>姓名升序排序>>>>>");
  135.   List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
  136.   System.out.println(sortNameEmployeeList);
  137.    
  138.   System.out.println(">>>>获取工资最高的前2条员工信息");
  139.   List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
  140.   System.out.println(dispaly2EmployeeList);
  141.    
  142.   System.out.println(">>>>获取平均工资");
  143.   OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
  144.   System.out.println(averageSalary);
  145.    
  146.   System.out.println(">>>>获取工作地点的平均工资");
  147.   OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
  148.   System.out.println(optionalDouble);
  149.    
  150.   System.out.println(">>>>>>Java8 Optional用法>>>>>>");
  151.   Optional<String> stringOptional = Optional.of("test");
  152.   System.out.println(stringOptional.get());
  153.    
  154.   Optional<String> isOptional = Optional.ofNullable("hello");
  155.   System.out.println(isOptional.isPresent());
  156.   System.out.println(isOptional.get());
  157.   System.out.println(isOptional.orElse("0"));
  158.    
  159.   System.out.println(">>>>>>>>>>>>");
  160.   //Optional<String> optionalVal = Optional.of(null);
  161.   // System.out.println(optionalVal);
  162.   Optional<String> optional = Optional.ofNullable("optional");
  163.   System.out.println(optional);
  164.   System.out.println(optional.isPresent());
  165.   System.out.println(optional.get());
  166.   System.out.println(optional.orElse("haha"));
  167.   System.out.println(">>>>>>>>>>>>");
  168.    
  169.   Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
  170.   System.out.println(employeeOptional_);
  171.    
  172.  

1.Java8 新特性介绍

原文链接 https://my.oschina.net/chenxiaobian/blog/704421,https://www.cnblogs.com/hmdrzql/p/6354010.html

现在我们有一个需求:给一个user组成的list 按照user的年龄排序。实现不难,代码如下:

 UserCompare是一个实现了Comprator的类

这种方法由于sort方法的第二个参数是Comparator 所以你要写一个实现类(我这里是UserCompare类),并且override该接口的实现方法。

java8提供了lambda来简化,有了lambda程序员从此不加班呀~    

刚才那个Comparator的实现类以及内部若干代码就都省了,代之以lambda表达式。

另外,IntelliJ会提示你改成更好的写法

实现类里有多少代码,你就省了多少行代码。

高兴了半天,到底是什么原理呢?其实是java8新提供的语法糖。

我们打开java1.8 Comparator的定义,发现了类定义上面多了一个@FunctionalInterface

对,1.8多了一个概念就是FunctionalInterface,这个Comparator就是一个FunctionalInterface

有了这个注解,原来使用实现类的地方就可以代之以lambda表达式。

 

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

  1.   Lambda表达式
  2.    
  3.   函数式接口
  4.    
  5.   Stream
  6.    
  7.   Optional
  8.    
  9.   Predicate
  10.    
  11.   Function
  12.    
  13.   Consumer
  14.    
  15.   Filter
  16.    
  17.   Map-Reduce
  18.    
  19.   新的Date API

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

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

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

基础类

  1.   @Data
  2.   @Builder
  3.   @AllArgsConstructor
  4.   @NoArgsConstructor
  5.   public class Person {
  6.    
  7.   private int id;
  8.   private String name;
  9.   private String address;
  10.    
  11.    
  12.   }

1.List操作

  1.   public class ExampleList {
  2.   private static List<String> items = new ArrayList<>();
  3.    
  4.   static {
  5.   items.add("A");
  6.   items.add("BC");
  7.   items.add("C");
  8.   items.add("BD");
  9.   items.add("E");
  10.   }
  11.    
  12.   public static void main(String[] args) {
  13.   //Java8之前操作List
  14.   for(String item:items){
  15.   System.out.println(item);
  16.   }
  17.    
  18.   //Java8 lambda遍历list
  19.   items.forEach(c-> System.out.println(c));
  20.    
  21.   items.forEach(item->{
  22.   if("C".equals(item)){
  23.   System.out.println(item);
  24.   }
  25.   });
  26.    
  27.   System.out.println("--------");
  28.    
  29.   //先过滤
  30.   items.stream().filter(s->s.contains("B")).forEach(c1-> System.out.println(c1));
  31.    
  32.   }
  33.   }

2.Map操作

  1.   public class ExampleMap {
  2.    
  3.   private static Map<String, Integer> items = new HashMap<>();
  4.    
  5.   static {
  6.   items.put("A", 10);
  7.   items.put("B", 20);
  8.   items.put("C", 30);
  9.   items.put("D", 40);
  10.   items.put("E", 50);
  11.   items.put("F", 60);
  12.   }
  13.    
  14.   public static void main(String[] args) {
  15.    
  16.   //Java8之前遍历是这样遍历map
  17.   for(Map.Entry<String,Integer> entry:items.entrySet()){
  18.   System.out.println("key:" + entry.getKey() + " value:" + entry.getValue());
  19.   }
  20.    
  21.   //Java8遍历map
  22.   items.forEach((key,value)-> System.out.println("key:" + key + " value:" + value));
  23.    
  24.    
  25.   }
  26.    
  27.    
  28.   }

3.Groupingby操作

  1.   /**
  2.   *
  3.   *Java8 Collectors.groupingBy and Collectors.mapping example
  4.   */
  5.   public class ExampleMapping {
  6.    
  7.   private static List<Person> personList = Lists.newArrayList();
  8.    
  9.   static {
  10.   personList.add(Person.builder().id(10).address("apple").address("shanghai").build());
  11.   personList.add(Person.builder().id(12).address("apple").address("wuhan").build());
  12.   personList.add(Person.builder().id(16).address("apple").address("nanjing").build());
  13.   }
  14.    
  15.   public static void main(String[] args) {
  16.   //分组
  17.   Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(c -> c.getAddress()));
  18.   System.out.println(collect);
  19.   }
  20.   }

4.List转换为Map

  1.   public class ExampleListConvertMap {
  2.    
  3.   private static List<Person> personList = Lists.newArrayList();
  4.    
  5.   static{
  6.   personList.add(Person.builder().id(20).name("zhangsan").address("shanghai").build());
  7.   personList.add(Person.builder().id(30).name("lisi").address("nanjing").build());
  8.   }
  9.    
  10.   public static void main(String[] args) {
  11.   //Java8 List转换Map
  12.   Map<Integer,Person> map_ = personList.stream().collect(Collectors.toMap((key->key.getId()),(value->value)));
  13.   map_.forEach((key,value)-> System.out.println(key + ":" + value));
  14.    
  15.   Map<Integer, Person> mappedMovies = personList.stream().collect(
  16.   Collectors.toMap(Person::getRank, Person::getData));
  17.    
  18.   }
  19.   }

5.FilterMap操作

  1.   public class ExampleFilterMap {
  2.    
  3.   private static Map<Integer,String> map_ = Maps.newHashMap();
  4.    
  5.   static{
  6.   map_.put(1, "linode.com");
  7.   map_.put(2, "heroku.com");
  8.   map_.put(3, "digitalocean.com");
  9.   map_.put(4, "aws.amazon.com");
  10.   }
  11.    
  12.   public static void main(String[] args) {
  13.   //before java iterator map
  14.   String result = null;
  15.   for(Map.Entry<Integer,String> entry:map_.entrySet()){
  16.   if("heroku.com".equals(entry.getValue())){
  17.   result = entry.getValue();
  18.   }
  19.   }
  20.    
  21.   System.out.println("Before Java 8 :" + result);
  22.    
  23.   //Java8 Map->Stream->Filter->String
  24.   result = map_.entrySet().stream().
  25.   filter(map->"heroku.com".equals(map.getValue()))
  26.   .map(map->map.getValue())
  27.   .collect(Collectors.joining());
  28.   System.out.println("Java 8 :" + result);
  29.    
  30.   Map<Integer,String> collect = map_.entrySet().stream()
  31.   .filter(c->c.getKey()==2)
  32.   .collect(Collectors.toMap(p->p.getKey(),p->p.getValue()));
  33.   System.out.println(collect);
  34.    
  35.   }
  36.   }

6.Optional操作可以防止NullPointException

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

7.给出一个详细的例子

  1.   @Data
  2.   @Builder
  3.   @AllArgsConstructor
  4.   @NoArgsConstructor
  5.   public class Employee {
  6.    
  7.   private String name;
  8.   private int salary;
  9.   private String office;
  10.   }
  11.    
  12.    
  13.   public class ExampleEmployee {
  14.    
  15.   private static List<Employee> employeeList = Lists.newArrayList();
  16.    
  17.   static{
  18.   employeeList.add(Employee.builder().name("Matt").salary(5000).office("New York").build());
  19.   employeeList.add(Employee.builder().name("Steve").salary(6000).office("London").build());
  20.   employeeList.add(Employee.builder().name("Carrie").salary(20000).office("New York").build());
  21.   employeeList.add(Employee.builder().name("Peter").salary(7000).office("New York").build());
  22.   employeeList.add(Employee.builder().name("Pat").salary(8000).office("London").build());
  23.   employeeList.add(Employee.builder().name("Tammy").salary(29000).office("Shanghai").build());
  24.   }
  25.    
  26.   public static void main(String[] args) {
  27.   //anyMatch
  28.   boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
  29.   System.out.println(isMatch);
  30.    
  31.   //返回所有salary大于6000
  32.   boolean matched = employeeList.stream().allMatch(employee -> employee.getSalary()>4000);
  33.   System.out.println(matched);
  34.    
  35.   //找出工资最高
  36.   Optional<Employee> hightestSalary = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
  37.   System.out.println(hightestSalary);
  38.    
  39.   //返回姓名列表
  40.   List<String> names = employeeList.stream().map(employee -> employee.getName()).collect(Collectors.toList());
  41.   System.out.println(names);
  42.    
  43.   //List转换成Map
  44.   Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
  45.   employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
  46.    
  47.   //统计办公室是New York的个数
  48.   long officeCount = employeeList.stream().filter(employee -> employee.getOffice().equals("Shanghai")).count();
  49.   System.out.println(officeCount);
  50.    
  51.   //List转换为Set
  52.   Set<String> officeSet = employeeList.stream().map(employee -> employee.getOffice()).distinct().collect(Collectors.toSet());
  53.   System.out.println(officeSet);
  54.    
  55.   //查找办公室地点是New York的员工
  56.   Optional<Employee> allMatchedEmployees = employeeList.stream().filter(employee -> employee.getOffice().equals("New York")).findAny();
  57.   System.out.println(allMatchedEmployees);
  58.    
  59.   //按照工资的降序来列出员工信息
  60.   List<Employee> sortEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
  61.   //按照名字的升序列出员工信息
  62.   List<Employee> sortEmployeeByName = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
  63.   System.out.println(sortEmployeeList);
  64.   System.out.println("按照名字的升序列出员工信息:" + sortEmployeeByName);
  65.    
  66.   //获取工资最高的前2条员工信息
  67.   List<Employee> top2EmployeeList= employeeList.stream()
  68.   .sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary()))
  69.   .limit(2)
  70.   .collect(Collectors.toList());
  71.   System.out.println(top2EmployeeList);
  72.    
  73.   //获取平均工资
  74.   OptionalDouble averageSalary = employeeList.stream().mapToInt(employee->employee.getSalary()).average();
  75.   System.out.println("平均工资:" + averageSalary);
  76.    
  77.   //查找New York
  78.   OptionalDouble averageSalaryByOffice = employeeList.stream().filter(employee -> employee.getOffice()
  79.   .equals("New York"))
  80.   .mapToInt(employee->employee.getSalary())
  81.   .average();
  82.   System.out.println("New York办公室平均工资:" + averageSalaryByOffice);
  83.    
  84.   }
  85.   }

8.Java8常见操作

  1.    
  2.   public class EmployeeTest {
  3.    
  4.   public static List<Employee> generateData() {
  5.   return Arrays.asList(new Employee("Matt", 5000, "New York"),
  6.   new Employee("Steve", 6000, "London"),
  7.   new Employee("Carrie", 10000, "New York"),
  8.   new Employee("Peter", 7000, "New York"),
  9.   new Employee("Alec", 6000, "London"),
  10.   new Employee("Sarah", 8000, "London"),
  11.   new Employee("Rebecca", 4000, "New York"),
  12.   new Employee("Pat", 20000, "New York"),
  13.   new Employee("Tammy", 9000, "New York"),
  14.   new Employee("Fred", 15000, "Tokyo"));
  15.   }
  16.    
  17.   public static Map<String, Integer> generateMapData() {
  18.   Map<String, Integer> items = Maps.newHashMap();
  19.   items.put("A", 10);
  20.   items.put("B", 20);
  21.   items.put("C", 30);
  22.   items.put("D", 40);
  23.   items.put("E", 50);
  24.   items.put("F", 60);
  25.    
  26.   return items;
  27.   }
  28.    
  29.    
  30.   @Test
  31.   public void testEmployee() {
  32.   List<Employee> results = generateData();
  33.    
  34.   //打印出名字是Steve的员工信息
  35.   results.forEach(c -> {
  36.   if (c.getName().equals("Steve")) {
  37.   System.out.println(c);
  38.   }
  39.   });
  40.    
  41.   System.out.println("---------");
  42.    
  43.   //找出年薪超过6000的员工
  44.   results.stream().filter(c -> c.getSalary() >= 60000).forEach(c -> System.out.println(c));
  45.    
  46.   System.out.println("--->>>>>>----");
  47.    
  48.   //java8遍历map
  49.   Map<String, Integer> map_ = generateMapData();
  50.   map_.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
  51.    
  52.   System.out.println("---->>>>分组>>>-----");
  53.    
  54.   //java8 分组操作
  55.   Map<String, List<Employee>> groupMap = results.stream().collect(Collectors.groupingBy(c -> c.getOffice()));
  56.   System.out.println(groupMap);
  57.    
  58.   System.out.println("---->>>>List转化为Map>>>----");
  59.   //List转化Map
  60.   Map<String, Object> map = results.stream().collect(Collectors.toMap(Employee::getName, Employee::getOffice));
  61.   map.forEach((key, value) -> System.out.println("key:" + key + "," + "value:" + value));
  62.    
  63.   System.out.println("---->>>>>>>----");
  64.   Map<Integer, Employee> employeeMap = results.stream().collect(Collectors.toMap((key -> key.getSalary()), (value -> value)));
  65.   employeeMap.forEach((key, value) -> System.out.println(key + "," + value));
  66.    
  67.   System.out.println("---->>遍历map>>>----");
  68.   //打印出值大于30的map
  69.   Map<String, Integer> resultMap = map_.entrySet().stream().filter(c -> c.getValue() > 30).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
  70.   resultMap.forEach((key, value) -> System.out.println(key + "=" + value));
  71.    
  72.   System.out.println(">>>>>>>>>>>>>>>");
  73.   //打印key=D的map
  74.   Map<String, Integer> mapResults = map_.entrySet().stream().filter(c -> c.getKey().equals("D")).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
  75.   mapResults.forEach((key, value) -> System.out.println(key + ">>>>" + value));
  76.    
  77.   System.out.println(">>>>>>>Optional>>>>>>>");
  78.   Optional<String> optional = Optional.of("hello");
  79.   System.out.println(optional.isPresent());
  80.    
  81.   }
  82.    
  83.   @Test
  84.   public void testEmployeeExample() {
  85.   //anyMatch
  86.   List<Employee> employeeList = generateData();
  87.   boolean isMatch = employeeList.stream().anyMatch(employee -> employee.getOffice().equals("London"));
  88.   System.out.println(isMatch);
  89.    
  90.   //allMatch
  91.   boolean matched = employeeList.stream().allMatch(employee -> employee.getOffice().equals("London"));
  92.   System.out.println(matched);
  93.    
  94.   //找出工资最高的
  95.   Optional<Employee> employeeOptional = employeeList.stream().max((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
  96.   System.out.println(employeeOptional);
  97.    
  98.   //找出工资最少的
  99.   Optional<Employee> employee = employeeList.stream().min((e1,e2)->Integer.compare(e1.getSalary(),e2.getSalary()));
  100.   System.out.println(employee);
  101.    
  102.   //返回姓名列表
  103.   List<String> names = employeeList.stream().map(c->c.getName()).collect(Collectors.toList());
  104.   System.out.println(names);
  105.    
  106.   System.out.println(">>>>>>>>>>>");
  107.   //List转化Map
  108.   Map<String,Employee> employeeMap = employeeList.stream().collect(Collectors.toMap((key->key.getName()),(value->value)));
  109.   employeeMap.forEach((key,value)-> System.out.println(key + "=" + value));
  110.    
  111.   //统计办公室是New York的个数
  112.   long officeCount = employeeList.stream().filter(c->c.getOffice().equals("New York")).count();
  113.   System.out.println(officeCount);
  114.    
  115.   long salaryCount = employeeList.stream().filter(c->c.getSalary()>60000).count();
  116.   System.out.println(salaryCount);
  117.    
  118.   //List转化为Set
  119.   Set<String> officeSet = employeeList.stream().map(c->c.getOffice()).distinct().collect(Collectors.toSet());
  120.   System.out.println(officeSet);
  121.    
  122.   Set<Integer> salarySet = employeeList.stream().map(c->c.getSalary()).distinct().collect(Collectors.toSet());
  123.   System.out.println(salarySet);
  124.    
  125.   //查找办公室地点是New York的员工
  126.   Optional<Employee> optionals = employeeList.stream().filter(c->c.getOffice().equals("New York")).findAny();
  127.   System.out.println(optionals);
  128.    
  129.   System.out.println(">>>>>工资降序排序>>>>>");
  130.   //按照工资的降序来列出员工信息
  131.   List<Employee> sortSalaryEmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).collect(Collectors.toList());
  132.   System.out.println(sortSalaryEmployeeList);
  133.    
  134.   System.out.println(">>>>>姓名升序排序>>>>>");
  135.   List<Employee> sortNameEmployeeList = employeeList.stream().sorted((e1,e2)->e1.getName().compareTo(e2.getName())).collect(Collectors.toList());
  136.   System.out.println(sortNameEmployeeList);
  137.    
  138.   System.out.println(">>>>获取工资最高的前2条员工信息");
  139.   List<Employee> dispaly2EmployeeList = employeeList.stream().sorted((e1,e2)->Integer.compare(e2.getSalary(),e1.getSalary())).limit(2).collect(Collectors.toList());
  140.   System.out.println(dispaly2EmployeeList);
  141.    
  142.   System.out.println(">>>>获取平均工资");
  143.   OptionalDouble averageSalary = employeeList.stream().mapToInt(c->c.getSalary()).average();
  144.   System.out.println(averageSalary);
  145.    
  146.   System.out.println(">>>>获取工作地点的平均工资");
  147.   OptionalDouble optionalDouble = employeeList.stream().filter(c->c.getOffice().equals("New York")).mapToInt(c->c.getSalary()).average();
  148.   System.out.println(optionalDouble);
  149.    
  150.   System.out.println(">>>>>>Java8 Optional用法>>>>>>");
  151.   Optional<String> stringOptional = Optional.of("test");
  152.   System.out.println(stringOptional.get());
  153.    
  154.   Optional<String> isOptional = Optional.ofNullable("hello");
  155.   System.out.println(isOptional.isPresent());
  156.   System.out.println(isOptional.get());
  157.   System.out.println(isOptional.orElse("0"));
  158.    
  159.   System.out.println(">>>>>>>>>>>>");
  160.   //Optional<String> optionalVal = Optional.of(null);
  161.   // System.out.println(optionalVal);
  162.   Optional<String> optional = Optional.ofNullable("optional");
  163.   System.out.println(optional);
  164.   System.out.println(optional.isPresent());
  165.   System.out.println(optional.get());
  166.   System.out.println(optional.orElse("haha"));
  167.   System.out.println(">>>>>>>>>>>>");
  168.    
  169.   Optional<Employee> employeeOptional_ = employeeList.stream().filter(c->c.getOffice().equals("New York")).findFirst();
  170.   System.out.println(employeeOptional_);
  171.    
  172.  

标签:map,stream,System,employeeList,使用,println,lambda,Java8,out
来源: https://www.cnblogs.com/coder-wzr/p/14410981.html