Java 8 mapToInt 和 toIntFunction 示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22444731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:45:46  来源:igfitidea点击:

Java 8 mapToInt and toIntFunction examples

javajava-8java-stream

提问by chiperortiz

i am testing the new major update from Java A.K.A Java 8is very interesting. i am using streams in particular i am using this simple code.

我正在测试 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;}        
}            

in this example i understand very clear but later i have seen also can accomplish it in this way.

在这个例子中我理解得很清楚,但后来我看到也可以通过这种方式完成它。

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

i have checked the method toIntFunctionand in fact have the following signature.

我已经检查了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);
}

as i can see the applyAsInt have a input and returns a int as long as i understand

因为我可以看到 applyAsInt 有一个输入并返回一个 int 只要我理解

this code

这段代码

MyPerson::getAge

calls

电话

public int getAge(){return age;}//please correct me at this point        

my question is.. the method getAgehave not parameters and returns a intbut the toIntFunctionreceive a parameter this is the part i dont understand.

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

the parameter from toIntFunctionis inferred or something

参数来自toIntFunction推断或其他东西

any help is hugely appreciate..

任何帮助都非常感谢..

thanks a lot

多谢

采纳答案by Radiodef

Remember a method reference is just a shortcut for a lambda. So an instance method reference is a lambda that calls that method on the argument. The type of the argument is the class given in the method reference. It helps to "unwrap" it.

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

MyPerson::getAge

Unwrap to a lambda:

展开为 lambda:

(MyPerson p) -> p.getAge()

Unwrap to an anonymous class:

解包到匿名类:

new ToIntFunction<MyPerson>() {
    @Override
    public int applyAsInt(MyPerson p) {
        return p.getAge();
    }
}

With a static method reference, the signature must match exactly, that is, the static method takes a Tand returns an int. With an instance method reference, the parameter Tof the lambda is the object the method gets called on.

对于静态方法引用,签名必须完全匹配,即静态方法采用 aT并返回 an int。对于实例方法引用,Tlambda的参数是调用该方法的对象。

回答by Zhedar

As for as I know MyPerson::getAgeis like a pointer to MyPersons getAge() method, which returns an int. So value.getAge()gets invoked in int applyAsInt(MyPerson value);. In other words: You just tell the stream, that it should use getAge()s return value from it's current MyPersoniteration variable to construct another collectionan IntStream.

至于我所知道MyPerson::getAge的就像一个指向MyPersons getAge() 方法的指针,它返回一个int. 所以value.getAge()int applyAsInt(MyPerson value);. 换句话说:你刚才告诉流,它应该使用getAge()的返回值从它当前的MyPerson迭代变量来构造另一个集合IntStream