如何重写Java 8 Streaming方法?

时间:2016-06-06 08:57:01

标签: java set compare entity java-stream

我有以下entity课程:

@Entity
@Table(name = "KENNEL")
public class KENNEL{


    //other fields and vars

    @OneToMany(cascade = CascadeType.MERGE, orphanRemoval = true)
    @JoinColumn(name = "KENNEL_ID", referencedColumnName = "ID", updatable = true, insertable = true)
    private Set<Dog> dogs;

    public DateTime getOldestDogInKennel(){
            return dogList.stream().min(Comparator.comparing(Dog::getBirthday))
                .get().getBirthday();
        }


}

如何重新编写getOldestDogInKennel方法,以便无需使用java 8流媒体?

请注意,此实体不会实施类似的界面。

3 个答案:

答案 0 :(得分:3)

通过使用Collections min获取Dog Object的min元素

Collections.min(dogList, new Comparator<Dog>() {

    @Override
    public int compare(Dog o1, Dog o2) {
        return o1.getBirthday().compareTo(o2.getBirthday()));
    }

}).getBirthday()

答案 1 :(得分:1)

我想那会的;

Date oldest = new Date();
for (int i=0; i< doglist.size(); i++){
   if (doglist.get(i).getBirthday().compareTo(oldest) < 0)   
      oldest = doglist.get(i).getBirthday();
}

return oldest;

答案 2 :(得分:1)

我不知道你以后要在程序中做什么。因此,此方法在方法的末尾具有最早的dog

public DateTime getOldestDogInKennel() {
    if (dogList.size() <= 0) { return null; }

    Dog dog = dogList.get(0);
    for (int i = 1; i < dogList.size(); i++) {
        Dog d = dogList.get(i);
        if (d.getBirthday().compareTo(dog.getBirthday()) < 0)) {
            dog = d;
        }
    }

    return dog.getBirthday();
}

不使用Compareable界面:

public DateTime getOldestDogInKennel() {
    if (dogList.size() <= 0) { return null; }

    Dog dog = dogList.get(0);
    for (int i = 1; i < dogList.size(); i++) {
        Dog d = dogList.get(i);
        if (d.getBirthday().getTime() < dog.getBirthday().getTime()) {
            dog = d;
        }
    }

    return dog.getBirthday();
}