8.8 以管道取代循环(Replace Loop with Pipeline)
资料参考:https://mkyong.com/java8/java-8-streams-filter-examples/
动机:简化了循环过程,代码的可读性更强
示例代码:
1 class Test { 2 public static void main(String[] args) { 3 List<String> fruits = Arrays.asList("apple", "orange", "banana"); 4 5 // method one 使用循环 6 List<String> resultsOfLoop = getFilterOutput(fruits, "orange"); 7 for (String result : resultsOfLoop) { 8 System.out.println(result); 9 } 10 11 System.out.println("================="); 12 13 // method two 使用管道运算 14 List<String> resultsOfPipeline = 15 fruits.stream().filter(fruit -> !"orange".equals(fruit)).collect(Collectors.toList()); 16 resultsOfPipeline.forEach(System.out::println); 17 } 18 19 private static List<String> getFilterOutput(List<String> fruits, @NonNull String filter) { 20 List<String> result = new ArrayList<>(); 21 for (String fruit : fruits) { 22 if (!filter.equals(fruit)) { 23 result.add(fruit); 24 } 25 } 26 return result; 27 } 28 }
运行结果:
1 apple 2 banana 3 ================= 4 apple 5 banana