1.1 查找所有的偶數并求和
public?static?void?p1()?{
? List<Integer> numbers = Arrays.asList(1,?2,?3,?4,?5,?6,?7,?8,?9,?10);
??int?sum = numbers.stream()
? ? ? .filter(num -> num %?2?==?0)
? ? ? .mapToInt(Integer::intValue)
? ? ? .sum() ;
? System.err.printf("result: %s%n", sum) ;
}
1.2?查找并打印長度大于 5 的字符串個數
public?static?void?p2() {
??List<String> strings =?Arrays.asList(
? ??"apple",?"banana",?"grape",?
? ??"watermelon",?"kiwi",?"orange");
??Long?count = strings.stream()
? ? ? .filter(str -> str.length() >?5)
? ? ? .count() ;
??System.err.printf("result: %s%n", count) ;
}
1.3 處理每一個元素最后返回新集合???????
public?static?void?p3()?{
? List<Integer> numbers = Arrays.asList(1,?2,?3,?4,?5);
? List<Integer> squares = numbers.stream()
? ? ? .map(num -> num * num)
? ? ? .collect(Collectors.toList()) ;
? System.err.printf("result: %s%n", squares) ;
}
將每一個元素進行平方操作,最后返回一個新的集合。輸出結果:
result:?[1, 4, 9, 16, 25]
1.4?找出整數列表中的最大元素???????
public?static?void?p4()?{
? List<Integer> numbers = Arrays.asList(10,?5,?25,?15,?30);
??int?max = numbers.stream()
? ? ? .mapToInt(Integer::intValue)
? ? ? .max()
? ? ? .getAsInt();
? System.err.printf("result: %s%n", max) ;
}
1.5 將列表中的所有字符串連接成一個字符串???????
public?static?void?p5() {
??List<String> fruits =?Arrays.asList("apple",?"banana",?"cherry","coconut",?"apple");
??String?concat =fruits.stream()
? ? ? .collect(Collectors.joining()) ;
??System.err.printf("result: %s%n", concat) ;
}
1.6 轉成大寫再排序???????
public?static?void?p6() {
??List<String> fruits =?Arrays.asList("apple",?"Banana",?"Grape",?"orange",?"kiwi");
??List<String> sortedUppercase = fruits.stream()
? ? ? .map(String::toUpperCase)
? ? ? .sorted()
? ? ? .collect(Collectors.toList());
??System.err.printf("result: %s%n", sortedUppercase) ;
}
先將字符串轉為大寫,然后在進行排序,輸出結果:
result:?[APPLE, BANANA, GRAPE, KIWI, ORANGE]
1.7 計算double類型平均值???????
public?static?void?p7()?{
? List<Double> doubles = Arrays.asList(1.0,?2.0,?3.0,?4.0,?5.0);
??double?average = doubles.stream()
? ? ? .mapToDouble(Double::doubleValue)
? ? ? .average()
? ? ? .getAsDouble() ;
? System.err.printf("result: %s%n", average) ;
}
1.8 刪除重復元素???????
public?static?void?p8() {
??List<String> words =?Arrays.asList("apple",?"banana",?"apple",?"orange",?"banana",?"kiwi");
??List<String> uniqueWords = words.stream()
? ? ? .distinct()
? ? ? .collect(Collectors.toList()) ;
??System.err.printf("result: %s%n", uniqueWords) ;
}
1.9 檢查所有元素是否符合條件???????
public?static?void?p9() {
??List<Integer> numbers =?Arrays.asList(2,?4,?6,?8,?10);
??boolean?allEven = numbers.stream()
? ? ? .allMatch(n -> n%2?==?0) ;
??System.err.printf("result: %s%n", allEven) ;
}
1.10 檢查集合中是否包含特定元素???????
public?static?void?p10()?{
? List<Integer> numbers = Arrays.asList(2,?4,?6,?8,?10);
? boolean exists = numbers.stream()
? ? ? .anyMatch(n -> n.equals(8)) ;
? System.err.printf("result: %s%n", exists) ;
}
1.11 查找流中最長的字符串???????
public?static?void?p11() {
??List<String> fruits =?Arrays.asList("apple",?"banana",?"cherry",?"coconut",?"apple") ;
? int max = fruits.stream()
? ? .mapToInt(String::length)
? ? .max()
? ? .getAsInt() ;
??System.err.printf("result: %s%n", max) ;
}
1.12 從流中刪除null值???????
public?static?void?p12() {
??List<String> fruits =?Arrays.asList("apple",?"banana",?"cherry",?null,"coconut",?"apple");
??List<String> nonNullValues = fruits.stream()
? ? ? .filter(Objects::nonNull)
? ? ? .collect(Collectors.toList()) ;
??System.err.printf("result: %s%n", nonNullValues) ;
}
過濾為null的值,輸出結果:
result:?[apple, banana, cherry, coconut, apple]
1.13 分組并查找最大值???????
public?static?void?p13() {
??List<Employee> employees =new?ArrayList<>() ;
? employees.add(new?Employee("Alice","HR",50000.0)) ;
? employees.add(new?Employee("Bob","IT",60000.0)) ;
? employees.add(new?Employee("Charlie","Finance",55000.0)) ;
? employees.add(new?Employee("David","IT",70000.0)) ;
? employees.add(new?Employee("Eva",?"HR",?45000.0)) ;
? employees.add(new?Employee("Frank","Finance",58000.0));
??Map<String,?Optional<Employee>> highestSalaryPerDept = employees.stream()
? ? ? .collect(Collectors.groupingBy(
? ? ? ? ??Employee::getDepartment,?
? ? ? ? ??Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))
? ? ? ));
? highestSalaryPerDept.forEach((key, value) -> {
? ??System.err.printf("部門: %s, \t最高薪: %s%n", key, value.get()) ;
? });
}
輸出結果:
2.14 查找列表中第二小的元素???????
public?static?void?p14()?{
? List<Integer> numbers = Arrays.asList(2,?4,?6,?8,?10) ;
? Optional<Integer> secondSmallest = numbers.stream()
? ? ? .distinct()
? ? ? .sorted()
? ? ? .skip(1)
? ? ? .findFirst() ;
? System.err.printf("result: %s%n", secondSmallest) ;
}
1.15 查找兩個列表的交集???????
public?static?void?p15()?{
? List<Integer> list1 = Arrays.asList(1,?2,?3,?4,?5) ;
? List<Integer> list2 = Arrays.asList(4,?5,?6,?7,8) ;
? List<Integer> intersection = list1.stream()
? ? ? .filter(list2::contains)
? ? ? .collect(Collectors.toList()) ;
? System.err.printf("result: %s%n", intersection) ;
}
1.16 并行處理提升性能
使用并行流可以通過BaseStream.parallel或Collection#parallelStream操作,如下計算1億個數的求和???????
public static void main(String[] args) {
double[] arr = IntStream.range(0,?100_000_000)
? ? ? .mapToDouble(i ->?new?Random().nextDouble() *?100000)
? ? ? .toArray() ;
? computeSumOfSquareRoots(arr);
}
public static void computeSumOfSquareRoots(double[] arr) {
double?serialSum = computeSerialSum(DoubleStream.of(arr));
? System.out.println("Serial Sum: "?+ serialSum);
double?parallelSum = computeParallelSum(DoubleStream.of(arr));
? System.out.println("Parallel Sum: "?+ parallelSum);
}
public static double computeSerialSum(DoubleStream stream) {
long?startTime = System.currentTimeMillis();
double?sum = stream.reduce(0.0D, (l, r) -> l + r) ;
long?endTime = System.currentTimeMillis();
? System.out.println("Serial Computation Time: "?+ (endTime - startTime) +?" ms");
return?sum;
}
public static double computeParallelSum(DoubleStream stream) {
long?startTime = System.currentTimeMillis();
double?sum = stream.parallel().reduce(0, (l, r) -> l + r) ;
long?endTime = System.currentTimeMillis();
? System.out.println("Parallel Computation Time: "?+ (endTime - startTime) +?" ms");
return?sum;
}
運行結果???????
SerialComputation?Time:?73?ms
SerialSum:?5.000114159154823E12
ParallelComputation?Time:?38?ms
ParallelSum:?5.000114159151367E12