特性
jdk8中使用了::的用法滤淳。就是把方法當(dāng)做參數(shù)傳到stream內(nèi)部瞻佛,使stream的每個元素都傳入到該方法里面執(zhí)行一下,雙冒號運算就是Java中的[方法引用],[方法引用]的格式是:
類名::方法名
注意此處沒有()娇钱。
案例:
表達(dá)式:
person -> person.getAge();
使用雙冒號:
Person::getAge
表達(dá)式:
new HashMap<>()
使用雙冒號:
HsahMap :: new
部分代碼案例
未使用雙冒號
public class MyTest {
public static void main(String[] args) {
List<String> a1 = Arrays.asList("a", "b", "c");
for (String a : a1) {
printValur(a);
};
a1.forEach(x -> MyTest.printValur(x));
}
public static void printValur(String str) {
System.out.println("print value : " + str);
}
}
使用后
a1.forEach(MyTest::printValur);
Consumer<String> consumer = MyTest::printValur;
a1.forEach(x -> consumer.accept(x));
未使用雙冒號:
List<String> list = a1.stream().map(x -> x.toUpperCase()).collect(Collectors.toList());
System.out.println(list.toString());
使用雙冒號:
ArrayList<String> collect = a1.stream().map(String::toUpperCase).collect(Collectors.toCollection(ArrayList::new));
System.out.println(collect.toString());