gpt4 book ai didi

java - 使用 Java 8 Lambda 表达式查找票据列表是否具有不同货币

转载 作者:行者123 更新时间:2023-11-30 02:50:09 24 4
gpt4 key购买 nike

我有一张纸币列表,每张纸币都有特定的货币。如果所有纸币的货币都相同,我想退回货币。如果其中任何一张纸币具有不同的货币,则抛出异常。如何使用 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;
}

最佳答案

您可以使用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);

请注意,您不能从 lambda 引发异常(在本例中)。所以你必须为此进行单独的检查。

关于java - 使用 Java 8 Lambda 表达式查找票据列表是否具有不同货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38960063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com