可能有人請解釋這一點:可能有人請解釋Date maxDate = list.stream()。map(u - > u.date).max(Date :: compareTo).get();
Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get();
可能有人請解釋這一點:可能有人請解釋Date maxDate = list.stream()。map(u - > u.date).max(Date :: compareTo).get();
Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get();
理解將是分解成小塊,最簡單的。想象一個持有Date object
的類:
static class Holder {
public Date date;
public Holder(Date d) {
super();
}
}
List<Holder> list= Arrays.asList(new Holder(new Date()));
// creates a Stream<Holder> having the list as the source
Stream<Holder> s1 = list.stream();
// creates a Stream<Date> by taking the previous elements from the Stream
// and mapping those to `Date date`
Stream<Date> s2 = s1.map(u -> u.date);
// consumes the stream by invoking max using the compareTo method
// two Date objects are Comparable by invoking compareTo
Optional<Date> optionalDate = s2.max(Date::compareTo);
// gets the maxValue from that Optional
// if the initial list is empty, your last get will throw a NoSuchElementException
Date maxDate = optionalDate.get();
請問您再說一句: /*** Stream
在這種情況下,'u'就是'Holder'的變量名稱。你可以將它命名爲任何你想要的。你也可以這樣聲明:'(Holder holder) - > holder.date';但類型通常由編譯器推斷。 – Eugene
Date maxDate =
list.stream() // create a Stream<TheElementTypeOfTheList>
.map(u -> u.date) // map each element of a Date, thus creating a Stream<Date>
.max(Date::compareTo) // find the max Date of the Stream
.get(); // return that max Date (will throw an exception if the
// list is empty)
請您再說一句:***流
歡迎來到Stack Overflow!請參考 [tour](https://stackoverflow.com/tour), 查看,並通讀[幫助中心](https://stackoverflow.com/help),特別是 [How請問一個好問題?](https://stackoverflow.com/help/how-to-ask) 和[我可以問什麼問題?](https://stackoverflow.com/help/on-話題)。 –
表達式'.max(Date :: compareTo)'不必要地創建一個自定義的比較器,它將調用'compareTo'方法,因爲'Date'實現'Comparable',所以'.max(Comparator.naturalOrder())'會做工作。 – Holger