JAVA:lambda example

Rojer.2017.09.27

已經很熟悉 C# 的語法了,近期要用 JAVA 反而覺得有點格格不入,超不習慣,趕緊來記錄一下,這篇主要是針對 String 的處理,另外一篇是針對 class 的處理。

測試資料

public static List<String> init(){
    return Arrays.asList("abcd", "bcde", "cdef","bcad","cabd","dcba","abcd","abdf");
}

Where
public static void Where(){
    List<String> lines = init();
    List<String> result = lines.stream().filter(x->x.equals("abcd")).collect(Collectors.toList());  
    for(String txt : result){
        System.out.println(txt);   
    }
}

FirstOrDefault
public static void FirstOrDefault(){
    List<String> lines = init();
    String result = lines.stream().filter(x->x.equals("abcd")).findFirst().orElse(null);
    
    if(result != null)
        System.out.println(result);   
    else         
        System.out.println("result is null");   
    
    result = lines.stream().filter(x->x.equals("ghij")).findFirst().orElse(null);
        
    if(result != null)
        System.out.println(result);   
    else         
        System.out.println("result is null");   
}

StartsWith
public static void StartsWith(){
    List<String> lines = init();
    List<String> result = lines.stream().filter(x->x.startsWith("ab")).collect(Collectors.toList());  
    for(String txt : result){
        System.out.println(txt);   
    }
}

Endswith
public static void Endswith(){
    List<String> lines = init();
    List<String> result = lines.stream().filter(x->x.endsWith("d")).collect(Collectors.toList());  
    for(String txt : result){
        System.out.println(txt);   
    }
}

Like
public static void Like(){
    List<String> lines = init();
    List<String> result = lines.stream().filter(x->x.contains("ab")).collect(Collectors.toList());  
    for(String txt : result){
        System.out.println(txt);   
    }
}

Sort
public static void Sort(){
    List<String> lines = init();
    lines.sort((x,y)->x.compareTo(y));
    for(String txt : lines){
        System.out.println(txt);   
    }
}

Distinct
public static void Distinct(){
    List<String> lines = init();
    List<String> result = lines.stream().distinct().collect(Collectors.toList());
    for(String txt : result){
        System.out.println(txt);   
    }
}

Count
public static void Count(){
    List<String> lines = init();
    Long count = lines.stream().filter(x->x.equals("abcd")).count();
    System.out.println(count);   
}


    Blogger Comment

0 意見: