关于双参数方法参考的困惑

时间:2016-12-08 02:00:06

标签: java lambda java-8 method-reference

我对这种方法参考语法感到有点困惑。

counter()预计BiFunction HighTemp::lessThanTemp HighTemp.lessThanTemp()是有效参数,尽管if (f.func(vals[i], v))只接受一个参数。

行中究竟发生了什么:import java.util.function.BiFunction; class Demo { static class HighTemp { private int hTemp; HighTemp(int ht) { hTemp = ht; } boolean lessThanTemp(HighTemp ht2) { return hTemp < ht2.hTemp; } } static <T> int counter(T[] vals, BiFunction<T,T,Boolean> f, T v) { int count = 0; for (int i=0; i < vals.length; i++) { if (f.apply(vals[i], v)) { // THIS LINE count++; } } return count; } public static void main(String args[]) { HighTemp[] weekDayHighs2 = { new HighTemp(32), new HighTemp(12), new HighTemp(24), new HighTemp(19), new HighTemp(18), new HighTemp(12), new HighTemp(-1), new HighTemp(13) }; int count = counter(weekDayHighs2, HighTemp::lessThanTemp, new HighTemp(19)); System.out.println(count + " days had a high of less than 19"); } }

MCVE:

from app import db

class songs (db.Model):
    SongID = db.Column(db.Integer,primary_key=True, autoincrement=False)
    Artist = db.Column(db.String(120), primary_key=True)
    Title = db.Column(db.String(120), primary_key = True)
    def __repr__(self):
            return "%s, %s, %d\n" %(self.Artist, self.Title, self.SongID)

class points(db.Model):
    SongID = db.Column(db.Integer, db.ForeignKey("songs.SongID"), nullable= False, primary_key=True)
    Genre = db.Column(db.String(25), primary_key=True)
    Points = db.Column(db.Integer)
    Date = db.Column(db.Date, primary_key=True)
    Rank = db.Column(db.Integer)
    def __repr__self(self):
            return "%d, %s, %d\n" %(self.SongID, self.Genre, self.Points)
class artist_points(db.Model):
    Artist = db.Column(db.String(120), primary_key=True)
    Points = db.Column(db.Integer)
    def __repr__self(self):
        return "%s, %d\n" %(self.Artist, self.Points)

class graphs(db.Model): 
    SongID = db.Column(db.String(120), db.ForeignKey("songs.SongID"), nullable = False, primary_key = True)
    URL = db.Column(db.String(120), primary_key=True)
    def __repr__self(self):
        return "%s, %s\n" %(self.SongID, self.URL)

1 个答案:

答案 0 :(得分:3)

查看relevant documentation,其中注明:

  

方法引用String::compareToIgnoreCase的等效lambda表达式将具有形式参数列表(String a, String b),其中ab是用于更好地描述此示例的任意名称。方法引用将调用方法a.compareToIgnoreCase(b)

换句话说,HighTemp::lessThanTemp等同于lambda表达式:

(a, b) -> a.lessThanTemp(b)