2017-07-03 32 views
-2

可能有人請解釋這一點:可能有人請解釋Date maxDate = list.stream()。map(u - > u.date).max(Date :: compareTo).get();

Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get(); 
+2

歡迎來到Stack Overflow!請參考 [tour](https://stackoverflow.com/tour), 查看,並通讀[幫助中心](https://stackoverflow.com/help),特別是 [How請問一個好問題?](https://stackoverflow.com/help/how-to-ask) 和[我可以問什麼問題?](https://stackoverflow.com/help/on-話題)。 –

+1

表達式'.max(Date :: compareTo)'不必要地創建一個自定義的比較器,它將調用'compareTo'方法,因爲'Date'實現'Comparable',所以'.max(Comparator.naturalOrder())'會做工作。 – Holger

回答

2

理解將是分解成小塊,最簡單的。想象一個持有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(); 
+0

請問您再說一句: /*** Stream s2 = s1.map(u - > u.date); ****/ 什麼是「你」在這裏?是clas的名字(例如:Holder)? –

+1

在這種情況下,'u'就是'Holder'的變量名稱。你可以將它命名爲任何你想要的。你也可以這樣聲明:'(Holder holder) - > holder.date';但類型通常由編譯器推斷。 – Eugene

3
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) 
+0

請您再說一句:***流 s2 = s1.map(u - > u.date); **** /什麼是「你」在這裏?是clas的名字(例如:Holder)? –