【问题标题】:comparing Instants in Java8比较 Java8 中的 Instant
【发布时间】:2018-10-20 06:54:36
【问题描述】:

我有这个对象:

public class MatchEvent implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    private Instant dateReceived;

    public Instant getDateReceived() {
        return dateReceived;
    }


    public void setDateReceived(Instant dateReceived) {
        this.dateReceived = dateReceived;
    }

}

我想按收到日期订购;

matchService
            .findAllByDay(today)
                .sorted(Comparator.comparing(MatchEvent::dateReceived))

但这似乎是不可能的,因为我遇到了编译错误:

Multiple markers at this line
    - The method comparing(Function<? super T,? extends U>) in the type Comparator is not applicable for the arguments 
     (MatchEvent::dateReceived)
    - The type MatchEvent does not define dateReceived(T) that is applicable here

【问题讨论】:

  • dateReceived 是一个私有字段。您需要一个公开的getDateReceived() method 才能使用 method 引用:Comparator.comparing(MatchEvent::getDateReceived)

标签: collections java-8 java-stream comparator icomparable


【解决方案1】:

class MatchEvent 内部声明一个名为getDateReceived() 的公共方法,如下所示:

public Instant getDateReceived(){
    return dateReceived;
}

那么你可以使用这个方法作为方法参考如下:

Comparator.comparing(MatchEvent::getDateReceived)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2017-11-22
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 2016-07-15
    相关资源
    最近更新 更多