我有一个笔记列表,每个笔记都有特定的货币。如果所有票据都具有相同的货币,我想要退货。如果其中任何一个音符具有不同的货币,则抛出异常。如何使用Java 8 lambda表达式实现它?
public class Money {
private List<NoteTO> notes;
public List<NoteTO> getNotes() {
return notes;
}
public void setNotes(List<NoteTO> notes) {
this.notes = notes;
}
}
public class NoteTO {
private Long noteId;
private String currency;
public Long getNoteId() {
return noteId;
}
public void setNoteId(Long noteId) {
this.noteId = noteId;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
我通过以下方式实现了这一目标。但是,想要使用Lambda表达式做同样的事情。
public void testMethod(){
String currencyResponse = null;
for(NoteTO note : notes){
currencyResponse = checkCurrency(currencyResponse, note);
}
System.out.println("Currency : "+currencyResponse);
}
public String checkCurrency(String currencyResponse, NoteTO note) throws Exception {
String currency = note.getCurrency();
if(currencyResponse == null){
return currency;
} else if(!currencyResponse.equals(currency)){
throw new Exception();
}
return currencyResponse;
}