Java Lambda Stream

VipSoft發表於2023-05-02

::方法使用

條件:lambada表示式的主體僅包含一個表示式,且lambada表示式只呼叫一個已經存在的方法;被引用的方法的引數列表與lambada表示式的輸入輸出一致

以下是Java 8中方法引用的一些語法:

  • 靜態方法引用(static method)語法:classname::methodname 例如:Person::getAge
  • 物件的例項方法引用語法:instancename::methodname 例如:System.out::println
  • 物件的超類方法引用語法: super::methodname
  • 類構造器引用語法: classname::new 例如:ArrayList::new
  • 陣列構造器引用語法: typename[]::new 例如: String[]:new
DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getKafkaConsumer(sourceTopic, groupId));

kafkaDS.map(line->{return JSON.parseObject(line);});
//Lambda 簡寫
kafkaDS.map(JSON::parseObject);
@Test
void printTest1() {
    List<String> list = Arrays.asList("a", "b", "c", "d");

    System.out.println("for  => ");
    for (String item : list) {
        AcceptMethod.printValue(item);
    }

    System.out.println("forEach => ");
    list.forEach(item -> AcceptMethod.printValue(item));


    System.out.println("forEach => ::");
    //list.forEach(new AcceptMethod()::printValue); //非靜態方法
    list.forEach(AcceptMethod::printValue);



    System.out.println("forEach list => ::");
    List<LoginUser> loginUserList = new ArrayList<>();
    LoginUser loginUser = new LoginUser();
    loginUser.setOs("iOS");
    loginUserList.add(loginUser);
    loginUser = new LoginUser();
    loginUser.setOs("Android");
    loginUserList.add(loginUser);
    loginUserList.forEach(AcceptMethod::printList);

}

public static class AcceptMethod {
    public static void printValue(String str) {
        System.out.println("print value : " + str);
    }


    public static void printList(LoginUser map) {
        System.out.println("print value : " + map.getOs());
    }
}

Stream 示例

public class Java8Tester {
   public static void main(String args[]){
      System.out.println("使用 Java 7: ");
        
      // 計算空字串
      List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
      System.out.println("列表: " +strings);
      long count = getCountEmptyStringUsingJava7(strings);
        
      System.out.println("空字元數量為: " + count);
      count = getCountLength3UsingJava7(strings);
        
      System.out.println("字串長度為 3 的數量為: " + count);
        
      // 刪除空字串
      List<String> filtered = deleteEmptyStringsUsingJava7(strings);
      System.out.println("篩選後的列表: " + filtered);
        
      // 刪除空字串,並使用逗號把它們合併起來
      String mergedString = getMergedStringUsingJava7(strings,", ");
      System.out.println("合併字串: " + mergedString);
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
        
      // 獲取列表元素平方數
      List<Integer> squaresList = getSquares(numbers);
      System.out.println("平方數列表: " + squaresList);
      List<Integer> integers = Arrays.asList(1,2,13,4,15,6,17,8,19);
        
      System.out.println("列表: " +integers);
      System.out.println("列表中最大的數 : " + getMax(integers));
      System.out.println("列表中最小的數 : " + getMin(integers));
      System.out.println("所有數之和 : " + getSum(integers));
      System.out.println("平均數 : " + getAverage(integers));
      System.out.println("隨機數: ");
        
      // 輸出10個隨機數
      Random random = new Random();
        
      for(int i=0; i < 10; i++){
         System.out.println(random.nextInt());
      }
        
      System.out.println("使用 Java 8: ");
      System.out.println("列表: " +strings);
        
      count = strings.stream().filter(string->string.isEmpty()).count();
      System.out.println("空字串數量為: " + count);
        
      count = strings.stream().filter(string -> string.length() == 3).count();
      System.out.println("字串長度為 3 的數量為: " + count);
        
      filtered = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.toList());
      System.out.println("篩選後的列表: " + filtered);
        
      mergedString = strings.stream().filter(string ->!string.isEmpty()).collect(Collectors.joining(", "));
      System.out.println("合併字串: " + mergedString);
        
      squaresList = numbers.stream().map( i ->i*i).distinct().collect(Collectors.toList());
      System.out.println("Squares List: " + squaresList);
      System.out.println("列表: " +integers);
        
      IntSummaryStatistics stats = integers.stream().mapToInt((x) ->x).summaryStatistics();
        
      System.out.println("列表中最大的數 : " + stats.getMax());
      System.out.println("列表中最小的數 : " + stats.getMin());
      System.out.println("所有數之和 : " + stats.getSum());
      System.out.println("平均數 : " + stats.getAverage());
      System.out.println("隨機數: ");
        
      random.ints().limit(10).sorted().forEach(System.out::println);
        
      // 並行處理
      count = strings.parallelStream().filter(string -> string.isEmpty()).count();
      System.out.println("空字串的數量為: " + count);
   }
    
   private static int getCountEmptyStringUsingJava7(List<String> strings){
      int count = 0;
        
      for(String string: strings){
        
         if(string.isEmpty()){
            count++;
         }
      }
      return count;
   }
    
   private static int getCountLength3UsingJava7(List<String> strings){
      int count = 0;
        
      for(String string: strings){
        
         if(string.length() == 3){
            count++;
         }
      }
      return count;
   }
    
   private static List<String> deleteEmptyStringsUsingJava7(List<String> strings){
      List<String> filteredList = new ArrayList<String>();
        
      for(String string: strings){
        
         if(!string.isEmpty()){
             filteredList.add(string);
         }
      }
      return filteredList;
   }
    
   private static String getMergedStringUsingJava7(List<String> strings, String separator){
      StringBuilder stringBuilder = new StringBuilder();
        
      for(String string: strings){
        
         if(!string.isEmpty()){
            stringBuilder.append(string);
            stringBuilder.append(separator);
         }
      }
      String mergedString = stringBuilder.toString();
      return mergedString.substring(0, mergedString.length()-2);
   }
    
   private static List<Integer> getSquares(List<Integer> numbers){
      List<Integer> squaresList = new ArrayList<Integer>();
        
      for(Integer number: numbers){
         Integer square = new Integer(number.intValue() * number.intValue());
            
         if(!squaresList.contains(square)){
            squaresList.add(square);
         }
      }
      return squaresList;
   }
    
   private static int getMax(List<Integer> numbers){
      int max = numbers.get(0);
        
      for(int i=1;i < numbers.size();i++){
        
         Integer number = numbers.get(i);
            
         if(number.intValue() > max){
            max = number.intValue();
         }
      }
      return max;
   }
    
   private static int getMin(List<Integer> numbers){
      int min = numbers.get(0);
        
      for(int i=1;i < numbers.size();i++){
         Integer number = numbers.get(i);
        
         if(number.intValue() < min){
            min = number.intValue();
         }
      }
      return min;
   }
    
   private static int getSum(List numbers){
      int sum = (int)(numbers.get(0));
        
      for(int i=1;i < numbers.size();i++){
         sum += (int)numbers.get(i);
      }
      return sum;
   }
    
   private static int getAverage(List<Integer> numbers){
      return getSum(numbers) / numbers.size();
   }
}

例項

/**
* java list 中的字元是否包括在另一個 list 中
*/
@Test
void anyMatchTest() {
    List<String> permission = Arrays.asList("A", "B", "D");
    List<String> arr = Arrays.asList("C", "D", "E", "F");
    boolean b = arr.stream().anyMatch(permission::contains);
    System.out.println("" + b);
}

/**
* 陣列轉Set\List
*/
void anyMatchTest() {
 String[] permsArr = "a,b,c".split(",");
 Set<String> permsSet = Arrays.stream(permsArr).collect(Collectors.toSet());
}

相關文章