雙冒號運算符就是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); }