JDK8中有双冒号的用法,就是把方法当做参数传到stream内部,使stream的每个元素都传入到该方法里面执行一下。
public class MyTest {
public static void printValur(String str){
System.out.println("print value : "+str);
}
public static void main(String[] args) {
List<String> al = Arrays.asList("a", "b", "c", "d");
al.forEach(AcceptMethod::printValur);
//下面的方法和上面等价的
Consumer<String> methodParam = AcceptMethod::printValur; //方法参数
al.forEach(x -> methodParam.accept(x));//方法执行accept
}
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
}
https://www.jianshu.com/p/e429c517e9cb
int sum = list.stream().mapToInt(Person::getAge).sum();
int sum = list.stream().map(Person::getAge).reduce(Interger::sum).get();
Double average = list.stream().collect(averagingInt(Person::getAge));
OptionalDouble average = list.stream().mapToInt(Person::getAge).average();
网友评论