所以,在大學里,我們正在使用 csv 檔案和流。現在我正在做一些功課,但我已經堅持了幾天了。我有一個 csv 檔案,其中包含一些關于事故的資料(如事故嚴重程度、受害者人數等),并且我有一個函式可以讀取該資料并將其轉換為事故物件串列(它具有每種型別的屬性csv具有的資料):
private Severity severity;
private Integer victims;
public Accident(Severity severity, Integer victims) {
this.severity = severity;
this.victims = victims;
}
我已將該串列保存在一個物件中,我可以使用以下命令呼叫該串列getAccidents():
private List<Accident> accidents;
public AccidentArchive(List<Accident> accidents) {
this.accidents = accidents;
public Map<Severity, Integer> getMaxVictimsPerSeverity() { //Not working correctly
return getAccidents().stream.collect(Collectors.toMap(Accident::getSeverity, Accident::getVictims, Integer::max));
現在,我必須創建一個功能,如標題所述。我認為映射鍵可能是嚴重性(這是一個具有輕微、嚴重和致命值的列舉),并且這些值可能是具有相同嚴重性的每起事故的最高受害者人數。例如,地圖輸出可能是:SLIGHT=1, SERIOUS=3, FATAL=5.
我曾嘗試使用 Collections、Collectors 和 Comparator 庫,但我找不到任何方法來劃分每個嚴重性值中的所有事故,獲取每個事故的最大受害者數量,然后將這兩個值保存在Map<Severity, Integer>地圖中。該功能現在以這種方式開始:
public Map<Severity, Integer> getMaxVictimsPerSeverity() { return getAccidents().stream().collect(Collectors.toMap(Accident::getSeverity, ...))然后我嘗試了很多東西,但我找不到任何方法讓它回傳我想要的東西。我還是個新手,很多東西我還不明白,所以問我是否忘記了什么。
uj5u.com熱心網友回復:
提供一個 value extractor 來獲取每個事故的受害者,并提供一個 reducer 來保留最多的受害者。
return getAccidents().stream()
.collect(Collectors.toMap(Accident::getSeverity, Accident::getVictims, Integer::max));
uj5u.com熱心網友回復:
您正在嘗試按嚴重性分組并計算每組中的事故數量。
Map<Severity, Long> counted = list.stream()
.collect(Collectors.groupingBy(Accident::getSeverity, Collectors.counting()));
這應該可以幫助您實作您正在尋找的東西。
這是一個作業示例:
import java.util.*;
import java.util.stream.*;
public class Test {
public static void main(String args[]) {
Accident a1 = new Accident(Severity.SLIGHT);
Accident a2 = new Accident(Severity.SERIOUS);
Accident a3 = new Accident(Severity.SLIGHT);
Accident a4 = new Accident(Severity.FATAL);
Accident a5 = new Accident(Severity.FATAL);
List<Accident> list= new ArrayList<>();
list.add(a1);
list.add(a2);
list.add(a3);
list.add(a4);
list.add(a5);
Map<Severity, Long> counted = list.stream()
.collect(Collectors.groupingBy(Accident::getSeverity, Collectors.counting()));
System.out.println(counted);
}
static class Accident{
Severity severtity;
Accident(Severity s){
this.severtity = s;
}
public Severity getSeverity(){
return severtity;
}
}
static enum Severity{
SLIGHT, SERIOUS, FATAL;
}
}
結果:{FATAL=2, SLIGHT=2, SERIOUS=1}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/480908.html
上一篇:FuncA接受輸入并回傳一個str。FuncB&C應該使用strA來創建strsB&C,而是再次提示來自FuncA的相同輸入
