Java 8 Lambda表達式之方法引用 ::雙冒號操作符


雙冒號運算符就是java中的方法引用,方法引用的格式是類名::方法名。

這里只是方法名,方法名的后面沒有括號“()”。--------> 這樣的式子並不代表一定會調用這個方法。這種式子一般是用作Lambda表達式,Lambda有所謂的懶加載,不要括號就是說,看情況調用方法。

例如:

表達式:

person ->person.getAge();

可以替換為

Person::getAge

表達式:

()-> new HashMap<>();

可以替換為

HashMap::new

這種方法引用或者是雙冒號運算對應的參數類型是Function<T,R>T表示傳入的類型,R表示返回的類型。比如表達式person -> person.getAge();傳入的參數是person,返回值是peron.getAge(),那么方法引用Person::getAge

就對應着Funciton<Person,Integer>類型。

示例代碼:把List<String>里面的String全部大寫並返回新的ArrayList<String>,在前面的例子中是這樣寫的。

@Test
public void convertTest(){
    List<String> collected = new ArrayList<>();
    collected.add("alpha");
    collected.add("beta");
    collected = collected.stream().map(string -> string.toUpperCase()).collect(collectors.toList());
    System.out.println(collected);      
}

使用雙冒號操作符之后編程了下面的形式:

@Test
public void TestConverTest(){
     List<String> collected = new ArrayList<>();
     collected.add("alpha");
     collected.add("beta");
     collected = collected.stream().map(String::toUpperCase).collect(collectors.toCollection(ArrayList::new));
    System.out.println(collected);     
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM