Java 函数式编程 - 集合


从 Java 8 开始,Java 中引入了流,并将方法添加到集合中以获取流。一旦从集合中检索到流对象,我们就可以在集合上应用各种函数式编程方面,例如过滤、映射、缩减等。请参阅下面的示例 -

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FunctionTester {    
   public static void main(String[] args) {               
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

      //Mapping
      //get list of unique squares
      List<Integer> squaresList = numbers.stream().map( i -> i*i)
         .distinct().collect(Collectors.toList());
      System.out.println(squaresList);

      //Filering 
      //get list of non-empty strings
      List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
      List<String> nonEmptyStrings = strings.stream()
         .filter(string -> !string.isEmpty()).collect(Collectors.toList());
      System.out.println(nonEmptyStrings);

      //Reducing
      int sum = numbers.stream().reduce((num1, num2) -> num1 + num2).orElse(-1);
      System.out.println(sum);
   } 
}

输出

[9, 4, 49, 25]
[abc, bc, efg, abcd, jkl]
25