Rahul Chandwani Rahul Chandwani - 3 months ago 10
Java Question

Find if a list of notes is having different currencies using Java 8 Lambda expressions

I have a list of notes with every note having a specific currency. I want to return currency if all the notes have the same currency. And if anyone one of the notes is having a different currency then, throw Exception. How can I implement this using Java 8 lambda expressions?

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;
}
}


I have achieved this through the following. But, want to do the same using Lambda expression.

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;
}

Answer

You can use Stream::allMatch.

List<Note> notes = ...;

String currency = notes.isEmpty() ? null : notes.get(0).getCurrency();
if(!notes.stream().allMatch(e -> currency.equals(e.getCurrency())))
    throw new Exception();

System.out.println("Currency : " + currency);

Note that you can not throw exceptions from a lambda (in this case). So you have do a separate check for that.

Comments