Java8新特性——lambda表達式.(案例:公司業務)

需求:現有一個員工姓名list,其中包含單字母索引.要求輸出一個字符串,去掉全部單字母,全部名字首字母大寫並用逗號隔開.java

 1 package cn._2.thecompanyprocess;
 2 
 3 import java.util.List;
 4 import java.util.stream.Collectors;
 5 
 6 public class Process {
 7 
 8     // BEGIN java8_process
 9     public String cleanNames(List<String> names) {
10         if (names == null) return "";
11         return names
12                 .stream()
13                 .filter(name -> name.length() > 1)
14                 .map(name -> capitalize(name))
15                 .collect(Collectors.joining(","));
16     }
17 
18     private String capitalize(String e) {
19         return e.substring(0, 1).toUpperCase() + e.substring(1, e.length());
20     }
21     // END java8_process
22 
23 
24     // BEGIN java8_process_parallel
25     public String cleanNamesP(List<String> names) {
26         if (names == null) return "";
27         return names
28                 .parallelStream()
29                 .filter(n -> n.length() > 1)
30                 .map(e -> capitalize(e))
31                 .collect(Collectors.joining(","));
32     }
33 // END java8_process_parallel
34 
35 }

測試類:api

 1 package cn._2.thecompanyprocess;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 public class Mmain {
 7 
 8     public static void main(String[] args) {
 9         @SuppressWarnings("serial")
10         List<String> list = new ArrayList<String>(){{
11             add("a");add("alic");add("art");add("c");add("curry");
12             add("f");add("fred");add("h");add("haha");add("harry");
13         }};
14         System.out.println(new Process().cleanNames(list));
15         System.out.println(new Process().cleanNamesP(list));
16     }
17 }
相關文章
相關標籤/搜索