Java8新特性——lambda表达式.(案例:公司业务)
需求:现有一个员工姓名list,其中包含单字母索引.要求输出一个字符串,去掉所有单字母,所有名字首字母大写并用逗号隔开.
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 }
测试类:
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 }