我正在测试来自 Java AKA 的新主要更新Java 8
非常有趣。我正在使用流,特别是我正在使用这个简单的代码。
private void getAvg()
{
final ArrayList<MyPerson>persons = new ArrayList<>
(Arrays.asList(new MyPerson("Ringo","Starr"),new MyPerson("John","Lennon"),new MyPerson("Paul","Mccartney"),new MyPerson("George","Harrison")));
final OptionalDouble average = persons.stream().filter(p->p.age>=40).mapToInt(p->p.age).average();
average.ifPresent(System.out::println);
return;
}
private class MyPerson
{
private final Random random = new Random();
private final String name,lastName;
private int age;
public MyPerson(String name,String lastName){this.name = name;this.lastName = lastName;this.age=random.nextInt(100);}
public MyPerson(String name,String lastName,final int age){this(name,lastName);this.age=age;}
public String getName(){return name;}
public String getLastName(){return lastName;}
public int getAge(){return age;}
}
在这个例子中我理解得很清楚,但后来我看到也可以通过这种方式完成它。
final OptionalDouble average = persons.stream().filter(p->p.age>=40)
.mapToInt(MyPerson::getAge).average();
average.ifPresent(System.out::println);
我已经检查了toIntFunction方法 ,实际上具有以下签名。
@FunctionalInterface
public interface ToIntFunction<T> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
int applyAsInt(T value);
}
我可以看到 applyAsInt 有一个输入并返回一个 int 只要我理解
这段代码
MyPerson::getAge
来电
public int getAge(){return age;}//please correct me at this point
我的问题是.. 该方法getAge
没有参数并返回一个int但toIntFunction接收一个参数这是我不明白的部分。
参数 fromtoIntFunction
是推断的或其他的
任何帮助都非常感谢..
多谢