Java 8 mapToInt和toIntFunction示例

chi*_*tiz 7 java java-8 java-stream

我正在测试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;}        
}            
Run Code Online (Sandbox Code Playgroud)

在这个例子中我非常清楚,但后来我也看到也可以用这种方式完成它.

final OptionalDouble average = persons.stream().filter(p->p.age>=40)
.mapToInt(MyPerson::getAge).average();
average.ifPresent(System.out::println);        
Run Code Online (Sandbox Code Playgroud)

我检查了方法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);
}
Run Code Online (Sandbox Code Playgroud)

正如我所知,applyAsInt有一个输入并返回一个int

这段代码

MyPerson::getAge
Run Code Online (Sandbox Code Playgroud)

电话

public int getAge(){return age;}//please correct me at this point        
Run Code Online (Sandbox Code Playgroud)

我的问题是..方法getAge没有参数并返回一个inttoIntFunction接收参数这是我不理解的部分.

参数来自toIntFunction推断或其他

任何帮助都非常感谢..

非常感谢

Rad*_*def 9

请记住,方法引用只是lambda的快捷方式.因此,实例方法引用是一个lambda,它在参数上调用该方法.参数的类型是方法引用中给出的类.它有助于"解开"它.

MyPerson::getAge
Run Code Online (Sandbox Code Playgroud)

打开lambda:

(MyPerson p) -> p.getAge()
Run Code Online (Sandbox Code Playgroud)

打开一个匿名类:

new ToIntFunction<MyPerson>() {
    @Override
    public int applyAsInt(MyPerson p) {
        return p.getAge();
    }
}
Run Code Online (Sandbox Code Playgroud)

使用静态方法引用时,签名必须完全匹配,即静态方法接受T并返回一个int.使用实例方法引用,Tlambda 的参数是调用方法的对象.